Use Nginx to do websockets agent tutorials _nginx

Source: Internet
Author: User
Tags require nginx server node server nginx reverse proxy

The WebSocket protocol provides a way to create a real-time two-way communication Web application that supports both the client and the server. As part of the HTML5 specification, WebSockets simplifies the difficulty of developing web real-time communication programs. The current mainstream browsers support WebSockets, including Firefox, IE, Chrome, Safari and Opera, and more and more server application frameworks are starting to support websockets.

To use WebSockets in enterprise products, multiple WebSocket servers are required to meet high performance and high availability. The load balancing layer needs to support the WebSocket protocol. Nginx has been supporting the WebSocket protocol since version 1.3 and can act as a reverse proxy for websocket applications and load balancing.

The WebSocket protocol differs from the HTTP protocol, but the handshake of the WebSocket protocol is compatible with HTTP, and it uses the HTTP upgrade protocol header to upgrade the connection from the HTTP connection to the WebSocket connection. This feature makes it easy for websocket applications to be applied to existing infrastructure. For example, WebSocket applications can use standard 80 and 443 HTTP ports, so you can pass existing firewall facilities.

The WebSockets application establishes a long connection between the client and the server, making it easy to develop real-time applications. The HTTP upgrade protocol header mechanism is used to upgrade the connection from the HTTP connection to the WebSocket connection, and the upgrade mechanism uses the upgrade protocol header and the connection protocol header. The reverse proxy server faces a number of challenges in supporting the WebSocket protocol. One challenge is that WebSocket is a piecemeal forwarding (hop-by-hop) protocol, so when a proxy server intercepts a upgrade request from a client, the proxy server needs to send its own upgrade request to the back-end server, including the appropriate request headers. Also, because the WebSocket connection is a long connection and is very different from the traditional HTTP end connection, the reverse proxy server also needs to allow these connections to be open (open) and not to shut down the connection because it is idle.

Nginx supports websockets communication by establishing a tunnel between the client and the back-end server. In order for Nginx to send a upgrade request from the client to a back-end server, upgrade and connection header information must be set explicitly. As shown below:

Copy Code code as follows:

location/wsapp/{
Proxy_pass Http://wsbackend;
Proxy_http_version 1.1;
Proxy_set_header Upgrade $http _upgrade;
Proxy_set_header Connection "Upgrade";
}

Once we have completed the above setup, Nginx can handle the WebSocket connection.

Nginx WebSockets Example

The following example describes how Nginx is acting for websocket. This example uses the WS module, which is based on the websocket implementation of the Node.js build. Nginx will serve as a reverse proxy server, and a back-end server is a simple websockets application using WS and Node.js. Examples of the commands used are tested on Ubuntu 13.10 and CentOS 6.5, but may require minor modifications for other operating systems. In this case, the IP address of the WebSocket server is the IP address of the 192.168.100.10,nginx server is 192.168.100.20. If you have not installed Node.js and NPM, you can install it with the following command:

For Debian/ubuntu:

Copy Code code as follows:

sudo apt-get install Nodejs NPM

For Rhel/centos:
Copy Code code as follows:

sudo yum install Nodejs NPM

On Ubuntu, Node.js will be installed as "Nodejs", but will be installed as "node" in CentOS. We use "node" uniformly in the example, so we'll create a symbolic connection on Ubuntu to allow us to use "node":
Copy Code code as follows:

Ln-s/usr/bin/nodejs/usr/local/bin/node

Then install WS:
Copy Code code as follows:

sudo npm install ws

Note: If you get an error: "Error:failed to fetch from REGISTRY:WS", then running the following command should solve the problem:
Copy Code code as follows:

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

Next, you can run sudo npm install WS again

WS module from/root/node_modules/ws/bin/wscat, we will use it for clients, but we need to create a program to serve as our server. Save the following code in a server.js file:

Copy Code code as follows:

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);
});
});

This program can be executed by using the following command:
Copy Code code as follows:

Node Server.js

The program outputs an initialization message, "Server started," and then listens on port 8010 to wait for the client to connect. It processes all requests received and outputs the received message to the console, and then returns a message to the client that contains the message. We want Nginx to proxy client requests that can be implemented through the following configuration:
Copy Code code as follows:

Map $http _upgrade $connection _upgrade {
Default upgrade;
' Close;
}
Upstream WebSocket {
Server 192.168.100.10:8010;
}
server {
Listen 8020;
Location/{
Proxy_pass Http://websocket;
Proxy_http_version 1.1;
Proxy_set_header Upgrade $http _upgrade;
Proxy_set_header Connection "Upgrade";
}
}

The above configuration allows Nginx to listen to Port 8020 and forward any received requests to the WebSocket server on the back end, allowing the backend server to better handle the WebSocket protocol. We can use Wscat as a client to test:

Copy Code code as follows:

/root/node_modules/ws/bin/wscat–connect ws://192.168.100.20:8020

The above command establishes a connection through the Nginx reverse proxy server and back-end WebSocket server, and you can send any message to the server, and the server returns a message. Every time you send a message to the client, you can see the output of the message on the back-end server, and then the client displays a message from the service side.
This is an example of an interaction:

Server:

Client:

$ node Server.js

Server started

Wscat–connect ws://192.168.100.20:8020

Connected (Press CTRL + C to quit)

> Hello

Received from Client:hello

< Server received from Client:hello

From this we can see that the client and the server can establish websockets communication through the Nginx reverse proxy, and the message can be continuously transmitted in both directions until the client or server disconnects. In order for Nginx to handle websocket connections correctly, you simply set the message headers to handle upgrade requests for upgrades from an HTTP connection to a websocket connection.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.