Sockit.io无法通过React Native连接到服务器

时间:2019-12-18 03:42:04

标签: react-native socket.io

我使用库socket.io-client": "2.3.0"尝试在React Native上使用sockit。

我尝试在服务器端使用简单的代码。

server.js

const
    io = require("socket.io"),
    server = io.listen(8000);

let
    sequenceNumberByClient = new Map();

// event fired every time a new client connects:
server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
    // initialize this client's sequence number
    sequenceNumberByClient.set(socket, 1);

    // when socket disconnects, remove it from the list:
    socket.on("disconnect", () => {
        sequenceNumberByClient.delete(socket);
        console.info(`Client gone [id=${socket.id}]`);
    });
});

// sends each client its current sequence number
setInterval(() => {
    for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
        client.emit("seq-num", sequenceNumber);
        sequenceNumberByClient.set(client, sequenceNumber + 1);
    }
}, 1000);

在客户端:

client.js

const
    io = require("socket.io-client"),
    ioClient = io.connect("http://localhost:8000");

ioClient.on("seq-num", (msg) => console.info(msg));

node server然后是node client

我可以在服务器端看到Client connected

但是即使在Android或IOS上,它也无法在我的React Native端工作。

我的React Native代码如下:

import io from 'socket.io-client';

const ioClient = io.connect("http://localhost:8000");
ioClient.on('connect', () => console.log('connected on React Native'));
ioClient.on("seq-num", (msg) => console.info(msg));

我看不到connected on React Native,并且服务器上没有任何反应。

任何帮助将不胜感激。

0 个答案:

没有答案