Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

socket.io

I have a socket.io app hosted in A2Hosting shared hosting and the problem is that it uses only xhr polling because there seems to be an error establishing socket handshake.

This is the error I'm receiving:

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 for 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]

client side

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

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

    })
like image 235
Rendell Lasola Avatar asked Nov 06 '22 21:11

Rendell Lasola


1 Answers

This works for me:

    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);
      });
    });
like image 173
lumisi Avatar answered Nov 14 '22 20:11

lumisi