在使用socket.io的时候遇到这样一个问题:websocket接收的消息的顺序错位了,然后看了一下浏览器的console的报错,提示连接到ws失败,然后在浏览器的开发者工具的网络中看了一下ws对应的消息里面报错:Error during WebSocket handshake: Unexpected response code: 200

查了一下发现是nginx没有配置的问题。

相关的类似的问题:

https://github.com/websockets/ws/issues/979

nginx官方文档提到的解决方法:

WebSocket proxying

需要注意的是:

location /chat/socket.io {
    proxy_pass <http://backend>;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

这里的backend就是ip地址或者域名,不需要加后缀/chat/socket.io。