对Websocket进行负载均衡
http {
// ...省略
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocketCluster {
ip_hash;
server 127.0.0.1:6181;
server 127.0.0.1:6182;
}
server {
listen 80;
proxy_pass httpCluster;
#域名可以有多个,用空格隔开
server_name localhost 127.0.0.1;
location /chat {
# proxy_pass 127.0.0.1:6181
proxy_pass websocketCluster
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
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 "upgrade";
}
}
// ...省略
}
socket.io负载均衡
###服务器
var chat = io.of('/chat');
chat.on('connection', function(socket){});
###客户端
var socket = require('socket.io-client')('http://localhost/chat');
由于服务器有很多虚拟主机需要代理,想通过/chat/路径对websocket分发,socket.io-client连接时一直无法连接。
#查看socket.io详细DEBUG信息
DEBUG=* node socketClient.js
engine.io-client:polling polling +0ms
engine.io-client:polling-xhr xhr poll +0ms
engine.io-client:polling-xhr xhr open GET: http://localhost/socket.io/?EIO=3&transport=polling&t=1445484908552-6&b64=1&sid=dwJSvjOsMPxKwnP9AAAB +0ms
从DEBUG信息中可以知道,socket.io通过http://localhost/socket.io/建立连接。
var io = require('socket.io')(httpServer,{
"path":"/chat", //客户端和服务器端都指定连接的Url
"serveClient": false });
或者将Nginx的路径改为/socket.io/
就好了。