简体   繁体   English

Socket.io 不适用于 android 本机反应

[英]Socket.io not working on android react native

I am trying to socket.io to react native.我正在尝试对 socket.io 做出原生反应。 It works perfectly fine on iOS device but doesn't work on android. I was doing some research and found out you need to usesCleartextTraffic="true".它在 iOS 设备上工作得很好,但在 android 上不起作用。我做了一些研究,发现你需要使用 usesCleartextTraffic="true"。

I did that and its still not working.我这样做了,但仍然无法正常工作。 Below is my code.下面是我的代码。 Any help would be really appreciated.任何帮助将非常感激。

server code服务器代码

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer)

io.on("connection", (socket) => {
    socket.on("hello",function (){
        io.emit("hello", "worldd");
    })
});

httpServer.listen(3000);

Client Side客户端

useEffect(()=> {


    try {
      const socket = io('http://localhost:3000');


      socket.on("hello", (param) => {
        console.log(socket.id); // x8WIv7-mJelg7on_ALbx
        console.log(param);
      });


    } catch (e) {

      console.log(e)

    }


  });

I found out what the issue was.我发现了问题所在。 I had put an actual url not use localhost ans it worked.我放了一个实际的 url 不使用 localhost ans 它有效。 I used ngrok for that我为此使用了ngrok

I think first you need to change the way you are setting up you server, change it to this instead as suggested by the documentation我认为首先您需要更改设置服务器的方式,按照文档的建议将其更改为此

const app = express();
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);

The calling socket emit and on seems to be correct so try this and let me know if it works.调用套接字 emit 和 on 似乎是正确的,所以试试这个,让我知道它是否有效。 you can also check full documentation here https://socket.io/get-started/chat您还可以在此处查看完整文档https://socket.io/get-started/chat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM