Nginx websocket Configuration

Source: Internet
Author: User
Tags node server

a · What is WebSocket

The WebSocket protocol can communicate more than once after a successful handshake from the HTTP protocol until the connection is closed. However, the handshake in WebSocket is compatible with the handshake in HTTP, which uses the Upgrade protocol header in HTTP to upgrade the connection from HTTP to WebSocket. This makes it easier for the WebSocket program to use existing infrastructure.

    websocket works on HTTP 80 and 443 ports and uses the prefix ws:// or wss:// for protocol labeling, when establishing a connection using the http/1.1 101 status code for protocol switching, the current standard does not support the use of HTTP directly between two clients to establish a websocket connection.

Two. create a node-based websocket service

Installing node. js and NPM

$ yum Install Nodejs NPM

install ws and Wscat modules

ws is the websocket implementation of NODEJS, which we use to build a simple websocket Echo Server.

wscatis an executable websocket client that is used to debug the WebSocket service properly.

NPM Install WS Wscat

Create a simple service side

$ vim Server.jsconsole.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); }); });

Running the service side

$ node Server.js server started

Verify that the server is starting normally

$ netstat-tlunp|grep 8010tcp6 0 0::: 8010:::* LISTEN 23864/nodejs

Using Wscat as a client test

wscatcommand to install the current user directory by defaultnode_modules/wscat/Table of contents, my location here is/root/node_modules/wscat/bin/wscat

输入任意内容进行测试,得到相同返回则说明运行正常。


$ cd/root/node_modules/wscat/bin/$./wscat--connect ws://127.0.0.1:8010connected (press CTRL + C to quit) > Hello< S Erver received from client:hello> Welcome to www.hi-linux.com< Server received from Client:welcome to Www.hi-linux . com

Three. use Nginx to reverse proxy for WebSocket

Installing Nginx
Yum-y Install Nginx
Configuring Nginx Websocket
$ vim /usr/local/nginx/conf/nginx.conf#  adds the following configuration in the HTTP context to ensure that nginx can handle normal HTTP requests. http{  map  $http _upgrade  $connection _upgrade {    default  upgrade;     '       close;  }  upstream  websocket {     #ip_hash;    server localhost:8010;       server localhost:8011;  }#  The following configuration is added in the server context, Location refers to the path used for the WebSocket connection.   server {    listen       80;     server_name localhost;    access_log /var/log/nginx/ Yourdomain.log;    location / {      proxy_pass  http://websocket;      proxy_read_timeout 300s;       proxy_set_header&nbsP host  $host;      proxy_set_header x-real-ip  $remote _addr;       proxy_set_header X-Forwarded-For  $proxy _add_x_forwarded_for;       proxy_http_version 1.1;      proxy_set_header  Upgrade  $http _upgrade;      proxy_set_header connection $ Connection_upgrade;}}}

The most important is to add the following two lines in the configuration of the reverse proxy, the other parts and the normal HTTP reverse proxy no difference.

Proxy_set_header Upgrade $http _upgrade;proxy_set_header Connection $connection _upgrade;

The key part of this is that the HTTP request has more of the following headers:

Upgrade:websocketConnection:Upgrade

these two fields indicate that the request server Upgrade protocol is websocket. After processing the request, the server responds with the following message # status Code 101


http/1.1 101 Switching ProtocolsUpgrade:websocketConnection:upgrade

Tells the client that the protocol has been successfully switched and upgraded to the WebSocket protocol. After the handshake succeeds, the server side and the client are equal, just like a normal socket, capable of two-way communication. Instead of interacting with HTTP, it begins to websocket data-frame protocol for data exchange.

Here the map instructions can be used to combine variables into a new variable, depending on whether the client comes with a upgrade header to determine whether to pass the connection header to the source station, the method is more elegant than the direct upgrade.

By default, the connection is closed after 60 seconds of no data transfer, and proxy_read_timeout the parameter can be extended at this time or the source station will keep the connection by periodically sending Ping frames to confirm that the connection is still in use.

Start Nginx

/etc/init.d/nginx start

Test access to the WebSocket service via Nginx

$ cd/root/node_modules/wscat/bin/$./wscat--connect ws://192.168.2.210connected (press CTRL + C to quit) > Hello nginx& Lt Server received from Client:hello nginx> Welcome to www.hi-linux.com< Server received from Client:welcome to Www.h I-linux.com

Test successful, OK

Nginx websocket Configuration

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.