WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

后端 未结 16 1445
攒了一身酷
攒了一身酷 2020-12-04 21:08

I am trying to integrate Socket.io with Angular and I\'m having difficulties making a connection from the client-side to the server. I\'ve looked through other related quest

相关标签:
16条回答
  • 2020-12-04 21:51

    Had the same issue, my app is behind nginx. Making these changes to my Nginx config removed the error.

    location / {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    }
    
    0 讨论(0)
  • 2020-12-04 21:52

    I solved this by removing io.listen(server);. I started running into this error when I started integrating passport.socketio and using passport middleware.

    0 讨论(0)
  • 2020-12-04 21:53

    Problem solved! I just figured out how to solve the issue, but I would still like to know if this is normal behavior or not.

    It seems that even though the Websocket connection establishes correctly (indicated by the 101 Switching Protocols request), it still defaults to long-polling. The fix was as simple as adding this option to the Socket.io connection function:

    {transports: ['websocket']}
    

    So the code finally looks like this:

    const app = express();
    const server = http.createServer(app);
    var io = require('socket.io')(server);
    
    io.on('connection', function(socket) {
      console.log('connected socket!');
    
      socket.on('greet', function(data) {
        console.log(data);
        socket.emit('respond', { hello: 'Hey, Mr.Client!' });
      });
      socket.on('disconnect', function() {
        console.log('Socket disconnected');
      });
    });
    

    and on the client:

    var socket = io('ws://localhost:3000', {transports: ['websocket']});
    socket.on('connect', function () {
      console.log('connected!');
      socket.emit('greet', { message: 'Hello Mr.Server!' });
    });
    
    socket.on('respond', function (data) {
      console.log(data);
    });
    

    And the messages now appear as frames:

    working websockets

    This Github issue pointed me in the right direction. Thanks to everyone who helped out!

    0 讨论(0)
  • 2020-12-04 21:53

    In your controller, you are using an http scheme, but I think you should be using a ws scheme, as you are using websockets. Try to use ws://localhost:3000 in your connect function.

    0 讨论(0)
提交回复
热议问题