nginx正常只能代理http请求,如果想实现代理websocket的需求,需在请求中加入"Upgrade"字段,使请求从http升级为websocket。
配置如下:
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
...
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1;
#以下配置添加代理头部:
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
实验案例:
配置websockeet服务器,客户端通过代理连接服务器端。环境如下:
websocket服务端:192.168.1.110:8010
nginx :192.168.1.131:8081
1:利用nodejs实现一个websocket服务端,监听8010端口,等待websocket链接。
安装nodejs与npm,并安装ws模块。(这里通过官网程序包实现)
[root@192_168_1_110 ~]# tar -zxvf node-v6.2.0-linux-x64.tar.gz[root@192_168_1_110 ~]# ln -s /root/node-v6.2.0-linux-x64/bin/node /usr/local/bin/node[root@192_168_1_110 ~]# ln -s /root/node-v6.2.0-linux-x64/bin/node /usr/local/bin/node[root@192_168_1_110 ~]# npm install -g ws[root@192_168_1_110 ~]# npm install -g wscat
编写websocket服务监听程序:
[root@192_168_1_110 ~]# 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);});});
启动websocket服务端:
[root@192_168_1_110 ~]# node server.jsServer started
重新开启一个终端,使用wscat程序测试程序连接:
[root@192_168_1_110 ~]# /root/node-v6.2.0-linux-x64/lib/node_modules/wscat/bin/wscat --connect ws://192.168.1.110:8010connected (press CTRL+C to quit)> This is a websocket test...< Server received from client: This is a websocket test...>
查看服务端:
[root@192_168_1_110 ~]#node server.jsServer startedReceived from client: This is a websocket test... ----从客户端接收到的信息
至此,websocket环境搭建完成。
2:配置nginx,代理110上的websocket链接。
[root@192_168_1_131 ~]# vim /opt/conf/nginx/nginx.conf......http {......map $http_upgrade $connection_upgrade {default upgrade;'' close;}.......include vhost/*.conf; [root@192_168_1_131 ~]# vim /opt/conf/nginx/vhost/nodejs.confupstream nodejs{server 192.168.1.110:8010;}server {listen 8010;access_log /opt/logs/nginx/nodejs.log main;location / {proxy_pass http://nodejs;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;}}
重新加载nginx配置:
[root@192_168_1_131 ~]# service nginx reload
这样配置过后,在nginx服务器*问8010端口的请求,将会全部发送到后端192.168.1.110的8081端口上。
3:验证websocket请求代理:(把ws地址指向192.168.1.131:8010)
[root@192_168_1_110 ~]# /root/node-v6.2.0-linux-x64/lib/node_modules/wscat/bin/wscat --connect ws://192.168.1.131:8010connected (press CTRL+C to quit)> This is a websocket test through nginx proxying...< Server received from client: This is a websocket test through nginx proxying...>
查看服务端:
[root@192_168_1_110 ~]#node server.jsServer startedReceived from client: This is a websocket test...Received from client: This is a websocket test through nginx proxying...
可以看到通过代理,websocket也能正常接收到客户端的请求信息。
本文出自 “扮演上帝的小丑” 博客,转载请与作者联系!