First we need to get a clear understand what is WebSocket all about and how it is operate. WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. It is used for applications such as chat, stock tickers, games . In traditional TCP/IP protocol, One who is responsible for initiating the communication with server is the client, and request is not send back to client unless the request is made previously.

  1. The way it works, is first a TCP connection needs to established between both . ie the connection is established by the client.
  2. When the connection is made, an HTTP request is sent through thatTCP connection by client.
  3. Vice verse, the same process happen from the server side, an HTTP response is sent through the sameTCP connection.

Once the connection is established from both sides, TCP connection is not needed anymore and usually becomes disconnected. The connections living on in case of an HTTP Upgrade request is made from the client (The client establishes a WebSocket connection through a process known as the WebSocket Handshake).

Client request (just like in HTTP, each line ends with \r\n and there must be an extra blank line at the end):

 

GET /chat HTTP/1.1

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

Sec-WebSocket-Protocol: chat, superchat

Sec-WebSocket-Version: 13

Origin: http://example.com

Server response:

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=

Sec-WebSocket-Protocol: chat

In traditional HTTP model of client initiated transactions the bandwidth consumption is more due to each and every HTML request, a bunch of headers and cookies data are transferred from the client machine to the Server. Web socket is implemented to overcome this bandwidth consumption. As we know WebSocket can be used for bi-directional “real-time” communication with multiple clients. I’ll describe here how NGINX as a WebSocket proxy.

NGINX working as a WebSocket proxy with Example:

For normal production use, when we need multiple WebSocket servers for performance and high availability, in such case we need a load balancing layer that understands the WebSocket protocol. Here, we refer NGINX as it supported WebSocket since version 1.3 and can be used as a reverse proxy and do load balancing of WebSocket applications.
The way NGINX work, it helps WebSocket by allowing a tunnel to be set up between a client and a backend server.

Example and how the setup is done.

In my opinion node.js is much better to implement WebSocket application as Node.js eliminates the waiting, and simply continues with the next request. These instructions have been tested with Ubuntu 13.10 and CentOS 6.5 but might need to be adjusted for other OSs and versions. we need two servers WebSocket and NGNIX with IPs 192.168.100.110 and 192.168.120 respectively.

 

  1. Make sure that Node.js and npm is installed. If not then run the following command:
    • For Debian and Ubuntu:

Sudo apt-get install nodejs npm

  • For RHEL and CentOS:

Sudo yum install nodejs npm

  1. In Ubuntu Node.js is installed as nodejs and as nodeon CentOS. Here we use node so we need to create a symbolic link from nodejs to node:

ln –s /usr/bin/nodejs /usr/local/bin/node

  1. In order to install ws, run the following command:

Sudo npm install ws

Note: In some case we get following error message: “Error: failed to fetch from registry: ws”, run the following command to fix the problem:

Sudo npm config set registry http://registry.npmjs.org/

Then run the command sudo npm install ws

  1. Create a program to act as the server. Create a file called jswith these contents:

console.log(“Server started”);
var Msg = ”;
var WebSocketServer = require(‘ws’).Server
, wss = new WebSocketServer({port: 8010});
wss.on(‘connection’, function(ws) {
ws.on(‘message’, function(message) {
console.log(‘Received from client: %s’, message);
ws.send(‘Server received from client: ‘ + message);
});
});

  1. To execute the server program, run the following command:

Node server.js

  1. Now the server will prints an initial message as “Server started” and then listens on port 8020, waiting for a client to connect. When the server receives a client request, it broadcast it and sends a message back to the client that containing the message acknowledged. In order to have NGINX proxy these requests, we create the following configuration:

http {
map $http_upgrade $connection_upgrade {
default upgrade;
” close;
}

upstream websocket {

server 192.168.100.110:8010;

}
server {

listen 8020;

location / {

proxy_pass http://websocket;

proxy_http_version 1.1;

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection $connection_upgrade;

}

}

}

  1. In order to test the server, we run wscat as our client:

$ /root/node_modules/ws/bin/wscat –connect ws://192.168.100.120:8020

The message we type is echoed to the client. Here’s a sample interaction:

Server: Client:
$ node server.js
Server started
wscat –connect ws://192.168.100.120:8020
Connected (press CTRL+C to quit)
> Hello
Received from client: Hello
< Server received from client: Hello

 

The above example help us to see that the client and server are able to communicate through NGINX as a proxy and messages can continue to be sent back and forth until either the client or server disconnects.

ServerAdminz provides Outsourced 24/7 Technical Support, Remote Server Administration, Server Security, Linux Server Management, Windows Server Management and Helpdesk Management to Datacenters, Hosting companies and ISPs around the world. We specialize in Extended Server Security, Server Hardening, Support of Linux/UNIX/Windows servers, products and services.If you are looking for a server management service provider, you can contact us on sales@serveradminz.com or +1 (845) 271 7172.

ServerAdminz is a server support company specialized in Outsourced 24/7 Web Hosting Support, Remote Infrastructure Management, NOC, Cloud and Enterprise Security Services. With over 10+ of years of experience in working with major Data Centers and ISPs with 130+ experienced technicians, we continue to manage more than 49,000 servers from 85+ countries and has bagged 5 international awards.

If you have any queries regarding server management services, share your thoughts and our representative will get back to you.

[two_third last=”yes” spacing=”yes” center_content=”no” hide_on_mobile=”no” background_color=”” background_image=”” background_repeat=”no-repeat” background_position=”left top” border_position=”all” border_size=”0px” border_color=”” border_style=”” padding=”” margin_top=”” margin_bottom=”” animation_type=”” animation_direction=”” animation_speed=”0.1″ class=”” id=””]

[/two_third]