Socket.IO 失败 : Error during WebSocket handshake: Unexpected response code: 400

标签 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

应用程序.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);
});
});

app.js 的 .htaccess
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);
        })

    })

最佳答案

这对我有用:

    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);
      });
    });

关于Socket.IO 失败 : Error during WebSocket handshake: Unexpected response code: 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54472842/

相关文章:

javascript - socket.io 仅在服务器端发出函数?

java - 如何使用 socket.io 发送二进制数据?

javascript - 使用 HighCharts 动态更新同一图表上的两个系列

javascript - 制作一个服务器模块以便在 Node.js 中重用

javascript - Socket.io 将数组传递给客户端

node.js - 错误视频流socket.io + socket.io-stream(超出最大调用堆栈大小)

node.js - 如何从 Express 服务器传递数据以响应 View ?

django - 使用Django+Redis+Socket.io搭建聊天室,从何入手?

node.js - Socket.IO和Electron无法发射或接收

node.js - 与 socket.io 一起使用时,express-session 未设置 session cookie