无法连接套接字本地

时间:2018-06-19 08:47:24

标签: react-native socket.io

我尝试连接socket in react native。我能够在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');
    });
});

React Native Code:

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

我在

中使用 socket.io-client 进行套接字连接

1 个答案:

答案 0 :(得分:2)

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

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