The net
module in Node.js allows us to create network connections. The connections that are created will be streams that we can write to and read from. This section will focus on just network connections and not HTTP. Node.js has a full HTTP module, and we will cover that in the next section.
All the functions assume that the net
module has been loaded like this:
var net = require('net');
This function will create a TCP server:
net.createServer([options], [listener])
This function allows us to listen for connections. The returned object will be a net.Server
object, and the connection listener will be passed to a net.Socket
object. We will cover both of these objects shortly.
Here is a simple example that shows us how to listen and write to a socket. Each connection will have to be manually closed:
var net = require('net'); var server = net.createServer(function (connection) { connection.write('You connected!'); }); server.listen(5000, function () { console.log('Listening on port 5000'); });
We will now look at the net.Server
object. All of the functions in the next section will need to a have a Server
object created through createServer
.
The net.Server
parameter is an EventEmitter
that will emit events. Here is a list of the events with the event argument if there is one:
net.Socket
close
Error
listening
Here is an example that uses all of the events:
var net = require('net'); var server = net.createServer(); server.on('listening', function () { console.log('I am listening'); }); server.on('connection', function (socket) { console.log(socket); socket.end(); server.close(); }); server.on('error', function (err) { console.log(err); }); server.on('close', function () { console.log('The server has stopped listening'); }); server.listen(5000);
This starts accepting connections:
server.listen(port, [host], [backlog], [callback])
Creating a server does not get it to start listening to requests. We will have to give the listen function at least a port. The host is optional, as it will listen on all IPv4 addresses, and the backlog will be the queue of connections. Finally, the callback will be called when the server starts listening.
You may get EADDRINUSE
. This just means that the port is already being used by another process.
Here is an example that defines all the parameters:
server.listen(5000, '127.0.0.1', 500, function () { console.log('Listening on port 5000'); });
This easily creates a connection to the specified address:
net.connect(port, [host], [connectListener]) net.createConnection(port, [host], [connectListener])
This function does not do anything that you cannot do with a socket. It is a convenient function that returns a net.Socket
object.
For the parameters, a port is required, the host will default to localhost, and connectListener
will be added to the connect event of the newly formed net.Socket
object.
Here is an example that will connect to a server we just created and send data every second:
var net = require('net'); var server = net.createServer(); server.on('listening', function () { console.log('I am listening'); }); server.on('connection', function (socket) { socket.on('data', function (d) { console.log('from client: ' + d); }); }); server.listen(5000); var client = net.connect({ port: 5000, host: 'localhost' }, function () { setInterval(function () { client.write('hey!'); }, 1000); });
This section will be similar to the net.Server
section. The net.Socket
parameter is the object that is returned anytime a connection is made. It can also be used to create a new connection.
It is a readable and writable stream. This is the only way to send and receive data from a net.Socket
.
Here is the list of events along with details of when they fire:
connect
: On connection.data
: When data is received.end
: When the socket has ended.timeout
: When the socket has timed out from inactivity. The socket is still open at this point.drain
: When all the data in the write buffer has been sent.Error
: On error.close
: When the socket closes.As net.Socket
is a readable stream, there is no read function. You will have to listen for the data event to the get the data.
Here is an example of using a socket to connect to a local server:
var server = net.createServer(); server.on('listening', function () { console.log('I am listening'); }); server.on('connection', function (socket) { socket.on('data', function (d) { console.log('from client: ' + d); }); }); server.listen(5000); var client = new net.Socket(); client.on('connect', function () { setInterval(function () { client.write('Hey!'); }, 1000); }); client.connect(5000, 'localhost');
socket.connect(port, [host], [listener])
This is the function that actually creates a connection. Much like net.connection
, the port is required, the host will default to localhost, and the listener just maps the function to the connection event.
Here is an example that connects locally and writes to the connection:
var client = new net.Socket(); client.on('connect', function () { setInterval(function () { client.write('Hey!'); }, 1000); }); client.connect(5000, 'localhost');
This sends data out on the socket:
socket.write(data, [encoding], [callback])
The socket is buffered because it is very easy to queue up more data than can be sent over the network. This is done automatically by Node.js, but you should be aware of this, as buffering will use up memory as it is holding the data to be sent.
The encoding parameter will default to UTF8, but any of the encodings we have discussed can be used. The callback will be called once the data has been written over the socket.
Here is an example with all of the parameters defined:
var client = new net.Socket(); client.on('connect', function () { client.write('This is the data', 'utf8', function(){ console.log('Data has been sent'); }); }); client.connect(5000, 'localhost');
This starts the closing process of the socket:
socket.end([data], [encoding])
This is effectively closing the socket. We cannot say for sure, but the reason could be that the server could send some data back, although the socket will close shortly.
You can send some data before the socket closes, and this is what the optional parameters are for:
Here is an example that closes a socket. var client = new net.Socket(); client.on('connect', function () { client.end('I am closing', 'utf8'); }); client.connect(5000, 'localhost');
3.142.200.109