【问题标题】:Why is Socket.io not connecting in my React Native app为什么 Socket.io 没有在我的 React Native 应用程序中连接
【发布时间】:2018-10-10 14:33:18
【问题描述】:

我正在创建一个 react 本机应用程序,并且我正在尝试将我的客户端应用程序连接到我的服务器。我正在使用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”,然后即使在客户端代码运行时也没有其他任何内容。请帮助我不确定我做错了什么。

【问题讨论】:

  • 需要更多细节。客户端是从哪个服务器提供服务的?他们在两个不同的服务器上吗?服务器端有控制台输出吗?
  • 一台服务器上的所有本地
  • 好的,很好。 React Native 应用程序是如何提供服务的?该部分未在此代码中显示 - 我希望在某处(或类似的东西)有一个 app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });

标签: javascript react-native socket.io


【解决方案1】:

我遇到了同样的问题,将“localhost”更改为实际的 ip,对我来说就像一个魅力。

所以改变

this.socket = SocketIOClient('http://localhost:1997');

this.socket = SocketIOClient('http://1962.168.xxx.xxx:1997');

我从这里得到了答案: Using Socket.io with React Native and not working

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多