Node by example

Node by example: 7. net module

7. net module

The complete source code can be downloaded here: http://github.com/Hendrik/node-by-example

With the release of node v0.1.91, the previously existing "tcp" module has been renamed to "net". It provides 2 main objects, net.Server, which is used to create a TCP or UNIX server, and net.Stream, which is an abstraction of a TCP or UNIX socket.

Use

require('dns')

to access the features of this module.

 

The following is a tcp server and client example that listens on port 8000.
See 07_net/net_server.js

// based on http://nodejs.org/api.html#net-server-183

var sys = require("sys"),
    net = require("net");

var server = net.createServer(function(stream) {
  stream.setEncoding("utf8");
  stream.addListener("connect", function() {
    sys.puts("Client connected");
    stream.write("hello\r\n");
  });
  stream.addListener("data", function(data) {
    sys.puts("Received from client: " + data);
    stream.write(data);
  });
  stream.addListener("end", function() {
    sys.puts("Client disconnected");
    stream.write("goodbye\r\n");
    stream.end();
  });
});
server.listen(8000, "localhost");

// stop the server after 10 secs
setTimeout(function() {
  server.close();
}, 10000);

 

Create the server and make it listen to port 8000 on "localhost":

var server = net.createServer(function(stream) { ... });
server.listen(8000, "localhost");

 

Set the encoding of the stream:

stream.setEncoding("utf8");

 

The net.Stream object instances are an EventEmitter with the following events: 'connect': emmited when a stream connection is successfully established
'data': emmited when data is received, comes with a 'data' argument, which will be a Buffer or a String
'end': emmited when the other end of the stream sends a FIN packet

The following code will output "Client connected" to the console and send "hello\r\n" to the client upon a successful connection:

stream.addListener("connect", function() {
  sys.puts("Client connected");
  stream.write("hello\r\n");
});

 

Whenever the client sends data, the script will output "Received from client: [data]" to the console and send the sent data back to the client:

stream.addListener("data", function(data) {
  sys.puts("Received from client: " + data);
  stream.write(data);
});

 

When the client ends the connection "Client disconnected" will be sent to the console and a "goodbye\r\n" will be sent to the client.
stream.end() then sends a FIN packet to the client:

stream.addListener("end", function() {
  sys.puts("Client disconnected");
  stream.write("goodbye\r\n");
  stream.end();
});

 

Additionally the server will be closed automatically after 10 seconds:

// stop the server after 10 secs
setTimeout(function() {
  server.close();
}, 10000);

 

In order to run the full example please first start the server via

node net_server.js

and then start the client via

node net_client.js

Then monitor the output in both consoles, which will be similar to:

net_server.js: Client connected
net_client.js: Client connected.
net_client.js: Response from server: hello
net_client.js: Sent to server: close
net_server.js: Received from client: close
net_client.js: Response from server: close
net_client.js: Response from server: goodbye
net_server.js: Client disconnected
net_client.js: Disconnected from server

 

Let's see what the client does:
See 07_net/net_client.js

var sys = require("sys"),
    net = require("net");

var client = net.createConnection(8000);
client.setEncoding("UTF8");

client.addListener("connect", function() {
  sys.puts("Client connected.");
  // close connection after 2sec
  setTimeout(function() {
    sys.puts("Sent to server: close");
    client.write("close", "UTF8");
  }, 2000);
});

client.addListener("data", function(data) {
  sys.puts("Response from server: " + data);
  if (data == "close") client.end();
});

client.addListener("close", function(data) {
  sys.puts("Disconnected from server");
});

 

Create the client and make it connect to port 8000. Set the encoding type to utf8.

var client = net.createConnection(8000);
client.setEncoding("UTF8");

 

net.createConnection() uses "localhost" by default, but you can change it to a different host, e.g.: 127.0.0.1, using:

net.createConnection(8000, "127.0.0.1");

 

As mentioned in the server example, the stream object comes with the "connect", "data" and "close" event emitters.

In this case the client will send "Client connected." to the console after a successful connection has been established and then start a timer to close the connection automatically after 2 seconds:

client.addListener("connect", function() {
  sys.puts("Client connected.");
  // close connection after 2sec
  setTimeout(function() {
    sys.puts("Sent to server: close");
    client.write("close", "UTF8");
  }, 2000);
});

 

When the client receives data from the server it will send "Response from server: [data]" to the console and in case the sent data is "close", it will also (half) close the stream by sending a FIN packet to the server:

client.addListener("data", function(data) {
  sys.puts("Response from server: " + data);
  if (data == "close") client.end();
});

 

Once the connection has been closed, the client will output "Disconnected from server" to the console:

client.addListener("close", function(data) {
  sys.puts("Disconnected from server");
});

 

This is just a basic example of a tcp server & client app, please refer to the official documentation for further details: http://nodejs.org/api.html#net-server-183