TCP Socket Programming in Node.js
Programming TCP Sockets in Node.js
Eager to know how sockets are programmed in Node? There are three variants of sockets in Node - i. TCP, ii. UDP, iii. UNIX domain. In this particular post, I will show you the basics of TCP socket programming in Node.js.
There are two categories of TCP socket programs you can write - i. server, ii. client. A TCP server listens for connections to it from clients and send data to the client. A TCP client connects to a TCP server exchange data with it. The communication between client and server happens via sockets.
Programming TCP sockets in Node requires the net
module, which is an asynchronous wrapper for network programming. The net
module is capable of many things, but for today we'll just focus on creating a TCP server and a client.
Writing a TCP Server
Here is an example of a very simple TCP server written in Node. Read the comments thoroughly, it explains how the code works.
var net = require('net'); var HOST = '127.0.0.1';
var PORT = 6969; // Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
sock.write('You said "' + data + '"');
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);
The same thing can be accomplished in a slightly different way. Make sure to include the necessary variables from the last example for this one to work.
var server = net.createServer();
server.listen(PORT, HOST);
console.log('Server listening on ' + server.address().address +':'+ server.address().port);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// other stuff is the same from here
});
So what's the difference? Basically they are the same thing, it's just we used different conventions of the JavaScript language. In the first example, we passed the connection
event handler to net.createServer()
, and chained the listen()
function. In the latter, we took a more 'conventional' approach. Either way works.
Writing a TCP Client
Now let's write a client to connect to the server we created. The following code creates a simple client which connects to the server, sends a message to server, and disconnects after getting a response from the server. Read the comments to follow the code.
var net = require('net'); var HOST = '127.0.0.1';
var PORT = 6969; var client = new net.Socket();
client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck Norris!'); }); // Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
}); // Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
So that's the very basics of TCP socket programming in Node.js, hope it helped you understand socket programming in Node better. Note that socket programming is a lot more than these simple examples. Once you start exchanging huge chunks of data and want to do complex things you will need to understand and use Streams and Buffers among other things.
Further Reading