WebSockets in Node.js

28 / Jul / 2016 by Rishabh Dixit 0 comments

About WebSocket

WebSocket is a protocol that provides full duplex communication i.e allows communication in both directions simultaneously. In this two way communication between web browser and server, both of them can send messages to one another at any point of time until the connection is open.

Once all the data gets transferred, the either of web browser or server can close the connection.

Creating WebSocket Server

Here i have used websocket npm module. You can install it using following command :

[xml]
npm install websocket
[/xml]

You can create a websocket server as follows :

[js]
var WebSocketServer = require(‘websocket’).server;
var http = require(‘http’);
var wsServer;
var server = http.createServer(function(request, response) {
console.log((new Date()) + ‘ Received request for ‘ + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ‘ Server is listening on port 8080’);
});

wsServer = new WebSocketServer({
httpServer: server
});

// listening request event
wsServer.on(‘request’, function(request) {
var connection = request.accept(‘echo-protocol’, request.origin);
console.log(‘Connection created at : ‘, new Date());

// listening message receiving event by client
connection.on(‘message’, function(message) {
if (message.type === ‘utf8’) {
console.log(‘Received Message: ‘ + message.utf8Data);

// Sending message to client
connection.sendUTF(message.utf8Data);
}
else if (message.type === ‘binary’) {
console.log(‘Received Binary Message of ‘ + message.binaryData.length + ‘ bytes’);

// Sending message to client in binary form
connection.sendBytes(message.binaryData);
}
});

// listening for connection close event
connection.on(‘close’, function(reasonCode, description) {
console.log(‘Peer ‘ + connection.remoteAddress + ‘ disconnected at : ‘, new Date());
});
});
[/js]

Here in above example its mandatory to mention httpServer because on top of this httpServer we will be mounting our new web socket server.

If we don’t mention this statement then our server will throw the following error :
“You must specify an httpServer on which to mount the WebSocket server.”

The reason behind making this statement mandatory is because the websocket protocol’s handshake process is interpreted by HTTP Servers only. Hence to establish a connection, client sends a WebSocket handshake request, for which the server returns a WebSocket handshake response. So once this connection gets established between client and server, the protocol then switches from Http to WebSocket i.e from onedirectional to bidirectional protocol. And because of this the server must be able to handle HTTP connections as well as WebSocket connections on the same port.

Creating WebSocket Client

After creating the server now lets create the client i.e WebSocket’s browser implementation using HTML/JS :

<html>
<body>
<div style="width: 100%;">
<textarea id="clientContent" cols="50" rows="10"></textarea>
<button onclick="sendMessage()">Send</button>
<textarea id="serverContent" style="margin-left: 10%;" cols="50" 		 rows="10"></textarea>
</div>
<script type="text/javascript">

var clientContent = document.getElementById('clientContent');
var serverContent = document.getElementById('serverContent');

// connecting to the web server
var socket = new WebSocket('ws://localhost:8080/','echo-protocol'); 

// listening for server response
socket.onmessage = function (message) { 
serverContent.innerHTML += message.data + '\n';
};

// listening for any socket error
socket.onerror = function (error) { 
console.log('WebSocket error: ' + error);
};

function sendMessage() {
if(clientContent && clientContent.value)
// sending message to server
socket.send(clientContent.value); 
clientContent.value='';
}

</script>
</body>
<html>

This above html/js example simply has two text boxes one for client to enter messages that need to be send to server and another for showing messages returned back from the server. For this example i have used the “echo-protocol”, in which the server sends back an identical copy of the data it receives.

Hope this blog helps you understanding WebSockets and their implementation in Node.js with the above given simple and short example.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *