Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expo with socket.io websocket failing to connect

I am attempting to connect to a socket.io server from within an Expo app. I am having issues being able to connect to my server. I have a web app that connect to the server fine, so the server is working OK. I have also looked at some examples, including one from the Expo repo, to no avail.

My client:

componentDidMount() {

    const socket = socketIOClient('http://192.168.1.210:80', {
      transports: ['websocket']
    });

    socket.on('connect', () => {
      console.log('Connected.');
    });

    socket.on('connect_error', (err) => {
      console.log(err);
    });
}

Server:

this.httpServer = HttpServer.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('');
});

this.httpServer.listen(80);

this.io = new IOServer({
  pingInterval: 10000,
  pingTimeout: 5000,
});

this.io.listen(this.httpServer);
this.io.set('transports', ['websocket']);

this.onConnection();

this.io.on('connection', (socket) => {/* events */}

The on connect event will never fire, only the connect_error event which simply says 'timeout'. Native websockets work fine when testing against https://www.websocket.org/echo.html.

like image 791
Gavin Avatar asked Nov 26 '25 08:11

Gavin


1 Answers

This was a bug with socket.io to do with loading in the incorrect WebSocket implementation.

It was looking for self.WebSocket, but self does not exist in React Native, so it was falling back to require('ws'), the Node.js implementation. In reality, it should have been using the native WebSocket implementation in React Native.

I've made a PR to solve this: https://github.com/socketio/engine.io-client/pull/607

The reason that turning on remote debugging makes it work is since the code runs in a browser (Chrome) in this mode, it's able to use the browser's WebSocket implementation.

like image 159
Ben Salili-James Avatar answered Nov 27 '25 22:11

Ben Salili-James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!