javascript - 带有 socket.io websocket 的 Expo 无法连接

标签 javascript react-native socket.io expo

我正在尝试从 Expo 应用程序连接到 socket.io 服务器。我在连接到我的服务器时遇到问题。我有一个可以正常连接到服务器的 Web 应用程序,因此服务器运行正常。我还查看了一些示例,包括 Expo 存储库中的示例,但无济于事。

我的客户:

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

服务器:

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 */}

on connect 事件永远不会触发,只会触发 connect_error 事件,它只是说“超时”。针对 https://www.websocket.org/echo.html 进行测试时, native websockets 工作正常.

最佳答案

这是 socket.io 的一个错误,与加载不正确的 WebSocket 实现有关。

它正在寻找 self.WebSocket,但是 self 在 React Native 中不存在,所以它退回到 require('ws'),Node.js 实现。实际上,它应该一直使用 React Native 中的原生 WebSocket 实现。

我已经发布了一个 PR 来解决这个问题:https://github.com/socketio/engine.io-client/pull/607

打开远程调试使其工作的原因是因为代码以这种模式在浏览器(Chrome)中运行,它能够使用浏览器的 WebSocket 实现。

关于javascript - 带有 socket.io websocket 的 Expo 无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650676/

相关文章:

html - 切换到 HTTPS 后无法连接到服务器

html - 使用 Node.js 调用 .send(data) 时在 HTML5 websocket 上接收 "Error: InvalidStateError: DOM Exception 11"

node.js - 套接字断开连接时是否必须删除事件监听器?

react-native - React-Native ScrollView 与自定义起始位置的中心对齐

ios - 无法读取未定义的属性 'string' 试图通过 react-native-create-bridge 理解 React Native Native 模块

python - 如何连接用Python制作的ML模型来 react native 应用程序

javascript - 如何使用 if-else 语句动态选择 div 类?

javascript - 选中复选框时触发该函数,未选中该函数则清除该函数

javascript - 为什么在 block 作用域外调用函数时没有得到 ReferenceError?

javascript - jQuery - 停止子级悬停触发父级单击相关元素