标签:nodejs node.js websocket 反向代理 负载均衡
Nginx担当WebSockets代理
英文原文:http://nginx.com/blog/websocket-nginx/
location /wsapp/ { proxy_pass http://wsbackend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
下面的例子讲述了Nginx是如何为WebSocket做代理的。此例将使用ws模块,它是基于node.js构建的WebSocket实现。Nginx将担当反向代理服务器,后端服务器是一个使用了ws和Node.js的简单WebSockets应用。例子使用的命令在Ubuntu 13.10和CentOS 6.5上测试通过,但对于其他操作系统或许需要稍作修改。就这个例子来说,WebSocket服务器的IP地址是192.168.100.10,Nginx服务器的IP地址是192.168.100.20。如果你还没有安装node.js和npm,你可以通过以下命令安装:
对 Debian/Ubuntu 来说:
sudo apt-get install nodejs npm
sudo yum install nodejs npm
ln -s /usr/bin/nodejs /usr/local/bin/node
sudo npm install ws
sudo npm config set registry http://registry.npmjs.org/
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); }); });
node server.js
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"; } }
/root/node_modules/ws/bin/wscat –connect ws://192.168.100.20:8020
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 |
由此我们可以看到客户端与服务器能通过Nginx反向代理建立WebSockets通信,而且消息可以持续地进行双向传输,直至客户端或服务器断开连接。为了让Nginx能正确处理WebSocket连接,只需正确地设置消息头来处理从HTTP连接升级到WebSocket连接的Upgrade请求。
Nginx担当WebSockets代理,布布扣,bubuko.com
标签:nodejs node.js websocket 反向代理 负载均衡
原文地址:http://blog.csdn.net/chszs/article/details/26369257