WebSocket握手响应400,但仍然有效

时间:2016-04-07 16:48:11

标签: node.js sockets nginx websocket socket.io

我使用socket.io在我的网站上建立聊天室,在我的计算机上运行时没有问题,但是当我在生产服务器上运行时,socket.io.js输出以下内容错误:

WebSocket connection to 'ws://myWebsite.com/socket.io/?EIO=3&transport=websocket&sid=1qtzy4QRde6G-PHkAAAU' failed: Error during WebSocket handshake: Unexpected response code: 400

我正在使用socket.io@1.4.5作为服务器和客户端

网站正在使用端口8080nginx后面的端口80上侦听,除了错误消息之外一切正常,但聊天室仍然正常运行,这很奇怪。< / p>

我在Stack Overflow上搜索了一些类似的问题,建议的解决方案已经是我的nginx设置(/etc/nginx/sites-enabled/myWebsite.com):

server {
        listen 80;
        server_name myWebsite.com;

        location / {
                proxy_pass http://127.0.0.1:8080;
                proxy_http_version 1.1;
                proxy_set_header Host $host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
        }
}

Meteor WebSocket handshake error 400 with nginx Meteor WebSocket connection to 'ws://.../websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

虽然聊天室仍然可以使用,但我仍然希望摆脱错误消息

供您参考,以下是socket.io相关代码:

// I use angular.js as the front-end framework
function Socket (socketFactory, $rootScope) {
    var ioSocket = io.connect(window.location.host);
    var socket = socketFactory({ioSocket : ioSocket});
    return {
        on: function (eventName, callback) {
            socket.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            });
        }
    };
}
Socket.$inject = ['socketFactory', '$rootScope'];
angular.module('core').factory('Socket', Socket);

Socket.on('new message', function (data) { ... });

1 个答案:

答案 0 :(得分:-1)

刚刚意识到我的网站正在使用CloudFlare,因为我已经禁用了代理,问题就解决了。