我正在尝试从 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/