Node.js Tutorial – 3 Creating a Chat Server using TCP Sockets


Previous tutorials on node.js could be found here: [1] [2]

We have learned to create a http server by using require(‘http’) and http.createServer(…).listen(port). The node.js is based on Javascript and event-driven model, which means that the events happen later (asynchronous). For example, node.js is single threaded, non-blocking. Every statement returns and carries on to the next statement. The events are like, when data is ready, when sockets are connected. The events are specified but may occur later.  This is highly-efficient and make node.js capable of handling thousands of requests at the same time without blocking.

The socket programming is usually seen in client/server architecture. The socket is the channel of the communication between any two programs (which can be on the same machine or distributed system). The socket contains a IP address and a port number (which should be unique, no two processes can use the same port on the same physical address space). The sockets can be written data to or read from.

In node.js, creating a server socket is easy. It needs to include the package net. The similar syntax/functions as http server are used. The following is a simple TCP server socket that implements a easy chat server. When the server is created, it listens to port 8080, which can of course be specified. The clients can join the server, in this case, we use ‘netcat‘ command line utility (you could pick telnet). When each client is connected, the server logs the message. When the client types a message (ended with ‘\n’), the message is broadcasted to all other joined-clients except itself.

A global array list sockets is used to keep the list of connected clients. When each client socket is established,  the socket is simply pushed to the array. When the client is about to close (destroy, disconnected), the socket will be deleted from the list.

We use sys package to print the message to the console, similar to console.log but shorter with sys.puts.

The source code written in node.js is given below.

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
// https://helloacm.com
// 09-Feb-2013
 
var sys = require('sys');
var net = require('net');
var sockets = [];
 
var svr = net.createServer(function(sock) {
    sys.puts('Connected: ' + sock.remoteAddress + ':' + sock.remotePort); 
    sock.write('Hello ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
    sockets.push(sock);
 
    sock.on('data', function(data) {  // client writes message
        if (data == 'exit\n') {
            sys.puts('exit command received: ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
            sock.destroy();
            var idx = sockets.indexOf(sock);
            if (idx != -1) {
                delete sockets[idx];
            }
            return;
        }
        var len = sockets.length;
        for (var i = 0; i < len; i ++) { // broad cast
            if (sockets[i] != sock) {
                if (sockets[i]) {
                    sockets[i].write(sock.remoteAddress + ':' + sock.remotePort + ':' + data);
                }
            }
        }
    });
 
    sock.on('end', function() { // client disconnects
        sys.puts('Disconnected: ' + data + data.remoteAddress + ':' + data.remotePort + '\n');
        var idx = sockets.indexOf(sock);
        if (idx != -1) {
            delete sockets[idx];
        }
    });
});
 
var svraddr = '127.0.0.1';
var svrport = 8080;
 
svr.listen(svrport, svraddr);
sys.puts('Server Created at ' + svraddr + ':' + svrport + '\n');
// https://helloacm.com
// 09-Feb-2013

var sys = require('sys');
var net = require('net');
var sockets = [];

var svr = net.createServer(function(sock) {
	sys.puts('Connected: ' + sock.remoteAddress + ':' + sock.remotePort); 
	sock.write('Hello ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
	sockets.push(sock);

	sock.on('data', function(data) {  // client writes message
		if (data == 'exit\n') {
			sys.puts('exit command received: ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
			sock.destroy();
			var idx = sockets.indexOf(sock);
			if (idx != -1) {
				delete sockets[idx];
			}
			return;
		}
		var len = sockets.length;
		for (var i = 0; i < len; i ++) { // broad cast
			if (sockets[i] != sock) {
				if (sockets[i]) {
					sockets[i].write(sock.remoteAddress + ':' + sock.remotePort + ':' + data);
				}
			}
		}
	});

	sock.on('end', function() { // client disconnects
		sys.puts('Disconnected: ' + data + data.remoteAddress + ':' + data.remotePort + '\n');
		var idx = sockets.indexOf(sock);
		if (idx != -1) {
			delete sockets[idx];
		}
	});
});

var svraddr = '127.0.0.1';
var svrport = 8080;

svr.listen(svrport, svraddr);
sys.puts('Server Created at ' + svraddr + ':' + svrport + '\n');

The server checks if the message from the clients are ‘exit’, if yes, the server will terminate the socket by using socket.destroy() method.

The sample usages are given below, first is the server side.

nodejs-chat1 Node.js Tutorial - 3 Creating a Chat Server using TCP Sockets beginner client-server http I/O File implementation internet javascript network nodejs programming languages sockets tcp/ip
The following shows three clients joining on the same machine (handy example) but using different ports.
nodejs-chat2 Node.js Tutorial - 3 Creating a Chat Server using TCP Sockets beginner client-server http I/O File implementation internet javascript network nodejs programming languages sockets tcp/ip
nodejs-chat3 Node.js Tutorial - 3 Creating a Chat Server using TCP Sockets beginner client-server http I/O File implementation internet javascript network nodejs programming languages sockets tcp/ip
nodejs-chat4 Node.js Tutorial - 3 Creating a Chat Server using TCP Sockets beginner client-server http I/O File implementation internet javascript network nodejs programming languages sockets tcp/ip

In the future, the example will be given on creating the client socket using node.js, here we just simply use the third party tools, e.g. netcat.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
930 words
Last Post: Silent Failure of Javascript
Next Post: Node.js Tutorial - 4 Reading File in node.js

The Permanent URL is: Node.js Tutorial – 3 Creating a Chat Server using TCP Sockets

4 Comments

  1. Roman
  2. Luke
  3. CD

Leave a Reply