Socket.IO失败:WebSocket握手期间出错:意外的响应代码:400

时间:2019-02-01 04:20:56

标签: socket.io

我在A2Hosting共享托管中托管了一个socket.io应用程序,问题是它仅使用xhr轮询,因为建立套接字握手似乎出错。

这是我收到的错误:

index.js:83 WebSocket connection to 'wss://www.xxxxxxx.com/socket.io/? 
EIO=3&transport=websocket&sid=7KqOx4VgE6xd507zAACf' failed: Error 
during WebSocket handshake: Unexpected response code: 400

app.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
const port = 65533

app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", 
"https://www.xxxxx.com/xxxx/xxxx");
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});

server.listen(port, () => console.log(`Example app listening on port 
${port}!`));

app.get('/', (req, res) => res.send('Socket is running....'))

// io.set('transports', ['websocket']);

io.on('connection', function (socket) {
  socket.on('scan_complete', function (data) {
  io.emit("scan_result", data);
console.log(data);
});
});

.htaccess用于app.js

RewriteEngine On
RewriteRule ^$ http://127.0.0.1:65533/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:65533/$1 [P,L]

客户端

$(function () {
        var socket = io.connect("https://www.xxxxx.com/");

        socket.on('scan_result', function (msg) {
            $('#content').html(profile);
        })

    })

2 个答案:

答案 0 :(得分:1)

这对我有用:

    const io = require('socket.io')(server, {
      serveClient: false,
      // below are engine.IO options
      origins: '*:*',
      transports: ['polling'],  <== this is what solved my problem
      pingInterval: 10000,
      pingTimeout: 5000,
      cookie: false
    });

    io.on('connection', socket => {
      console.log('IO Connected!', socket.id);

      ...

      socket.on('disconnect', () => {
        console.log('User disconnected!', socket.id);
      });
    });

答案 1 :(得分:0)

尝试在传输中添加websocket

var socket = io(
                  'wss://www.xxxxx.com', 
                  { transports: ['websocket'] }
               );


socket.on('connect', function () {
  console.log('connected!');
  socket.emit('greet', { message: 'I am connected !' });
});

socket.on('scan_result', function (data) {
  console.log(data);
});