当前位置 主页 > 服务器问题 > nginx问题汇总 >

    详解nginx websocket配置

    栏目:nginx问题汇总 时间:2018-11-19 16:23

    这篇文章主要介绍了详解nginx websocket配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    一·什么是websocket

    WebSocket协议相比较于HTTP协议成功握手后可以多次进行通讯,直到连接被关闭。但是WebSocket中的握手和HTTP中的握手兼容,它使用HTTP中的Upgrade协议头将连接从HTTP升级到WebSocket。这使得WebSocket程序可以更容易的使用现已存在的基础设施。

    WebSocket工作在HTTP的80和443端口并使用前缀ws://或者wss://进行协议标注,在建立连接时使用HTTP/1.1的101状态码进行协议切换,当前标准不支持两个客户端之间不借助HTTP直接建立Websocket连接。

    二.创建基于Node的WebSocket服务

    安装node.js和npm

    $ yum install nodejs npm

    安装ws和wscat模块

    ws是nodejs的WebSocket实现,我们借助它来搭建简单的WebSocket Echo Server。

    wscat是一个可执行的WebSocket客户端,用来调试WebSocket服务是否正常。

    npm install ws wscat

    创建一个简单的服务端

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

    运行服务端

    $ node server.js Server started

    验证服务端是否正常启动

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

    使用wscat做为客户端测试

    wscat命令默认安装当前用户目录node_modules/wscat/目录,我这里的位置是/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< Server received from client: Hello> Welcome to www.hi-linux.com< Server received from client: Welcome to www.hi-linux.com

    三.使用Nginx对WebSocket进行反向代理

    安装Nginx

    yum -y install nginx

    配置Nginx Websocket

    $ vim /usr/local/nginx/conf/nginx.conf# 在http上下文中增加如下配置,确保Nginx能处理正常http请求。http{ map $http_upgrade $connection_upgrade {  default upgrade;  ''   close; } upstream websocket {  #ip_hash;  server localhost:8010;   server localhost:8011; }# 以下配置是在server上下文中添加,location指用于websocket连接的path。 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 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;}}}