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

后端 未结 16 1449
攒了一身酷
攒了一身酷 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: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!

提交回复
热议问题