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.js 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); }); });启动websocket服务器:
再次打开终端设备,应用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:8010 connected (press CTRLC to quit) > This is a websocket test... < Server received from client: This is a websocket test... >查询服务器端:
[root@192_168_1_110 ~]#node server.js Server started Received from client: This is a websocket test... ----从手机客户端接受到的信息内容至此,websocket自然环境构建完毕。
2:代理110上配备nginx,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.conf upstream 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:8010 connected (press CTRLC to quit) > This is a websocket test through nginx proxying... < Server received from client: This is a websocket test through nginx proxying... >查询服务器:
可以看出,根据代理的说法,websocket也可以正常接收手机客户端所需的信息内容。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)