【问题标题】:Not able to connect socket in react native无法在本机反应中连接套接字
【发布时间】:2018-06-19 08:47:24
【问题描述】:

我正在尝试在本机反应中连接套接字。我可以在 html 文件中连接相同的套接字。

服务器代码:

const express = require("express")
    , app = express()
    , http = require("http").createServer(app)
    , fs = require("fs")
    , io = require("socket.io")(http);


app.use(express.static("public"));

http.listen("8080", () => {
    console.log("Server Started");
});

function socketIdsInRoom(name) {
    var socketIds = io.nsps['/'].adapter.rooms[name];
    if (socketIds) {
        var collection = [];
        for (var key in socketIds) {
            collection.push(key);
        }
        return collection;
    } else {
        return [];
    }
}

io.on('connection', function (socket) {
    console.log('connection');

    socket.on('disconnect', function () {
        console.log('disconnect');
    });
});

反应原生代码:

import io from 'socket.io-client';

const socket = io.connect('http://127.0.0.1:8080', { transports: ['websocket'] });

//const socket = io("http://127.0.0.1:8080"); /* I've also tried this */
socket.on('connect', function (data) {
    console.log('connect');
});

我在 react native 中使用 socket.io-client 进行套接字连接

【问题讨论】:

  • 任何控制台日志错误?
  • @Metalik 无。我已经用react-native log-android检查了它

标签: react-native socket.io


【解决方案1】:

问题与127.0.0.1 ip 有关。 Android无法连接到127.0.0.1 ip,因为它是内部环回IP。

您应该将127.0.0.1 替换为您的服务器IP ether 外部或内部IP。

【讨论】:

  • 改ip后就可以了。感谢您的回复。
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 2019-03-24
  • 2011-11-04
  • 1970-01-01
相关资源
最近更新 更多