-
Notifications
You must be signed in to change notification settings - Fork 0
/
time_server.js
76 lines (55 loc) · 2.34 KB
/
time_server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
Wite a TCP time server!
Your server should listen to TCP connections on port 8000. For each
connection you must write the current date & 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 07:42
----------------------------------------------------------------------
HINTS:
The `net` module from Node core has a method named
`net.createServer()` that takes a callback function. Unlike most
callbacks in Node, the callback used by `createServer()` is called
more than once. Every connection received by your server triggers
another call to the callback. The callback function has the signature:
function (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)
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:
/home/anca/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 `moment` package from npm.
Details of this excellent time/date handling library can be found
here: http://momentjs.com/docs/
----------------------------------------------------------------------
*/
var net = require('net');
var moment = require('moment');
var server = net.createServer(function(socket) {
socket.write(moment().format("YYYY-MM-DD HH:mm") + "\n");
socket.end();
});
server.listen(8000);