我正在创建一个 react native 应用程序,并且我正在尝试将我的客户端应用程序连接到我的服务器。我正在使用 socket-io,到目前为止我还没有成功连接两者。这是我在客户端的代码:
import SocketIOClient from 'socket.io-client';
(...)
if (result.type === "success") {
console.log("Here 1");
this.socket = SocketIOClient('http://localhost:1997');
this.socket.emit('test', 'Hello world!');
console.log("Here 2");
}
此代码输出“Here 1”“Here 2”
我的服务器代码如下:
let express = require('express');
let http = require('http')
let socketio = require('socket.io');
var app = express();
var server = http.Server(app);
var websocket = socketio(server);
let port = 1997;
server.listen(port, () => console.log('listening on *:' + port));
websocket.on('connection', (socket) => {
console.log("Client joined on " + socket.id);
websocket.on('test', function(data){
console.log('Data Receieved: ' + data);
});
});
此代码输出“listening on *:1997”,然后即使客户端代码运行,也不会输出任何其他内容。请帮忙,我不确定我做错了什么。
最佳答案
我遇到了同样的问题,并将“localhost”更改为实际的 ip,对我来说就像一个魅力。
所以改变
this.socket = SocketIOClient('http://localhost:1997');
至
this.socket = SocketIOClient('http://192.168.xxx.xxx:1997');
我从这里得到了答案: Using Socket.io with React Native and not working
关于javascript - 为什么 Socket.io 无法在我的 React Native 应用程序中连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742648/