a blog for those who code

Sunday, 27 December 2015

How to create WebSocket Server in Node.js

In this post we will be discussing about creating a WebSocket server in Node.js. For creating a WebSocket server we will be using ws module that will receive and respond to WebSocket requests from the browser.

According to ws, it is a simple to use WebSocket implementation, up-to-date againts RFC-6455. They claim to be fastest WebSocket library for node.js.


Creating WebSocket Server

var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var server = new WebSocketServer({port:8075});

server.on('connection', function(socket) {
  socket.on('message', function(message) {
    console.log(message + ' Received');

    if(message === 'CodingDefined') {
      socket.send('CodingDefined Blog!!!');
    }
  });

  socket.on('close', function(msg, disconnect) {
    console.log(msg + ' ' + disconnect);
  });
});

In the above code we have first created a WebSocket server from the ws module. Now the server which we have created will listen to its connection event which will supply it with a socket element for every incoming connection like below :

server.on('connection', function(socket) { });

Now inside our callback we will be interacting with the socket element and listening to message and close events. Now if the message received by the socket is "CodingDefined" we will reply with "CodingDefined Blog!!!".

WebSocket servers start out as HTTP Servers, then the browser connects to the HTTP server and asks to upgrade. When we pass port when initializing WebSocketServer, it creates an HTTP server that listens on port 8075 and accepts WebSocket upgrade requests.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

1 comment:

  1. The ws module is great, the slackbotapi module relies on it heavily - nice write up!

    ReplyDelete