简体   繁体   中英

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 .

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.

is it related to the https issue?, tried on localhost works on https, but http, seems the https://github.com/expo/examples/tree/master/with-socket-io mentioned something about

React Native provides a socket-io compatible WebSocket implementation, some people get tripped up on the https requirement so this example helps to clarify how you can get it running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM