FreeCodeCamp and Learning Node: Time Server

So our next challenge is to build a Time Server.  This one wasn’t too bad.  The only tricky part for me was using the outside library, namely the formatting of the date.

Here are the Directions and Hints:

TIME SERVER (Exercise 10 of 13)
  Write a TCP time server!
  Your server should listen to TCP connections on the port provided by the first argument to your program. For each connection you must write the current date & 24 hour time in the format:
     “YYYY-MM-DD hh:mm”
  followed by a newline character. Month, day, hour and minute must be zero-filled to 2 integers. For example:
     “2013-07-06 17:42”
  After sending the string, close the connection.
 ─────────────────────────────────────────────────────────────────────────────
 ## HINTS
  For this exercise we’ll be creating a raw TCP server. There’s no HTTP involved here so we need to use the net module from Node core which has all the basic networking functions.
  The net module has a method named net.createServer() that takes a function. The function that you need to pass to net.createServer() is a connection listener that is called more than once. Every connection received by your server triggers another call to the listener. The listener function has the signature:
     function listener(socket) { /* … */ }
  net.createServer() also returns an instance of your server. You must call server.listen(portNumber) to start listening on a particular port.
  A typical Node TCP server looks like this:
     var net = require(‘net’)
     var server = net.createServer(function (socket) {
       // socket handling logic
     })
     server.listen(8000)
  Remember to use the port number supplied to you as the first command-line argument.
  The socket object contains a lot of meta-data regarding the connection, but it is also a Node duplex Stream, in that it can be both read from, and written to. For this exercise we only need to write data and then close the socket.
  Use socket.write(data) to write data to the socket and socket.end() to close the socket. Alternatively, the .end() method also takes a data object so you can simplify to just: socket.end(data).
  Documentation on the net module can be found by pointing your browser here:
  file:///home/ubuntu/.nvm/versions/node/v4.4.3/lib/node_modules/learnyounode/node_apidoc/net.html
  To create the date, you’ll need to create a custom format from a new Date() object. The methods that will be useful are:
     date.getFullYear()
     date.getMonth()     // starts at 0
     date.getDate()      // returns the day of month
     date.getHours()
     date.getMinutes()
  Or, if you want to be adventurous, use the strftime package from npm. The strftime(fmt, date) function takes date formats just like the unix date command. You can read more about strftime at:

  [https://github.com/samsonjs/strftime] ( https://github.com/samsonjs/strftime )

The actual documentation link is:

https://nodejs.org/dist/latest-v6.x/docs/api/net.html

Okay, let’s get rolling. Since I decided to be adventurous, we need to install strftime.  We get:

$ npm install strftime
npm WARN package.json chat-example@0.0.0 No repository field.
npm WARN package.json chat-example@0.0.0 No license field.

strftime@0.9.2 node_modules/strftime

On to the actual program. First, I took the skeleton they give us above:

</pre>
</div>
<div>var net = require('net')</div>
<div>     var server = net.createServer(function (socket) {</div>
<div>       // socket handling logic</div>
<div>     })</div>
<div>     server.listen(8000)</div>
<div>

Now, 8000 isn’t going to necessarily be the socket we want.  We need to use the argument supplied to us.  As always, that’s the third element in process.argv (even though it says first in the hints – I think they mean it’s the first usable argument).  I added that and ran it and the terminal hung up; I figured out that it was still listening because I never told it to stop.  So, I added socket.end() inside var server (where it says “socket handling logic” was a hint to put it there) and I added a console.log to print out the port number to see if I had a working program so far.

Hey, build a little, test a little.  That was one of the mottoes of the moon program and NASA back in the 60s, and it works for me!

 

Here’s what I had so far:

</pre>
</div>
<div>var net = require('net');</div>
<div>var strftime = require('strftime');</div>
<div>var port = process.argv[2];</div>
<div></div>
<div>var server = net.createServer(function (socket) {</div>
<div>        console.log(port);</div>
<div>       // socket handling logic</div>
<div>       socket.end();</div>
<div>     });</div>
<div>     server.listen(port);</div>
<div>

That gives us the output I was looking for.  Obviously, we want our program to do a little more than that, so let’s have a look at the documentation for strftime using the link they gave us.  Note first, of course, that we need to use a require statement.  Next, we see some examples.

</pre>
</div>
<div>console.log(strftime('%B %d, %Y %H:%M:%S')), which returns April 28, 2011 18:21:08</div>
<div></div>
<div>console.log(strftime('%F %T', new Date(1307472705067))), which returns 2011-06-07 18:51:45</div>
<div>

Now, we’re going to need today’s date, so we add a variable for it using the JavaScript Date.now() function.  We want to printout the date and the time, less the seconds.  Returning to the documentation for strftime, we can see that to do that, we can use the first part of the second example, ‘%F’, and most of the last part of the first example, %H:%M. So, now I had:

</pre>
</div>
<div>var net = require('net');</div>
<div>var strftime = require('strftime');</div>
<div>var port = process.argv[2];</div>
<div></div>
<div>var today = Date.now();</div>
<div></div>
<div>var server = net.createServer(function (socket) {</div>
<div>        var data = (strftime('%F %H:%M', new Date(today)));</div>
<div></div>
<div>       // socket handling logic</div>
<div>       socket.end(data);</div>
<div>     });</div>
<div>     server.listen(port);</div>
<div>

This prints the date out correctly, but still doesn’t pass!!!  What???

I got this back:

Your submission results compared to the expected:
                 ACTUAL                                 EXPECTED
────────────────────────────────────────────────────────────────────────────────
   “2016-05-21 16:21”                  ==    “2016-05-21 16:21”
                                                 !=    “”
────────────────────────────────────────────────────────────────────────────────

  ✗  Submission results did not match expected!

Now, what was going on?

Simple: the directions specify that the date must be followed by a newline character.  I added it and lo and behold, my program passed!

</pre>
</div>
<div>var net = require('net');</div>
<div>var strftime = require('strftime');</div>
<div>var port = process.argv[2];</div>
<div></div>
<div>var today = Date.now();</div>
<div></div>
<div>var server = net.createServer(function (socket) {</div>
<div>        var data = (strftime('%F %H:%M', new Date(today))) + '\n';</div>
<div></div>
<div>       // socket handling logic</div>
<div>       socket.end(data);</div>
<div>     });</div>
<div>     server.listen(port);</div>
<div>

And there we go!  See you next time!

Advertisements

One thought on “FreeCodeCamp and Learning Node: Time Server

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s