資料內(nèi)容:
How it works...
Our server uses net.createServer to instantiate a TCP server.
This returns an object with a listen method which is called with two
arguments, 1337 and localhost, which instruct our server to listen on port 1337
on the local loop network interface.
The net.createServer method is passed a connection handler function, which is
called every time a new connection to the server is established.
This function receives a single argument--the socket.
We listen for a data event on the socket and then send the data back to the
client embedded inside a greeting message, by passing this greeting to the
socket.write method.
We also listen for a close event, which will detect when the client closes the
connection, and log a message if it does.
Our client uses the net.connect method, passing it the same port and hostname
as defined in our server, which in turn returns a socket.
We immediately write the name to the socket and attach a data listener in order
to receive a response from the server. When we get a response, we simply log
it to the terminal. We have to call the toString method on incoming data
because sockets deliver raw binary data in the form of Node buffers (this
string conversion happens implicitly on our server when we embed the buffer
into the greeting string).
Finally, our client also listens for a close event, which will trigger in cases
where the server ends the connection.