1

I am trying to socket.io to react native. 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".

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)

    }


  });
json2021
  • 2,146
  • 2
  • 14
  • 28
  • What happens when it's not working? Is there an [exception](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) (or https://reactnative.dev/docs/debugging)? – zapl Oct 01 '22 at 00:10

2 Answers2

3

I found out what the issue was. I had put an actual url not use localhost ans it worked. I used ngrok for that

json2021
  • 2,146
  • 2
  • 14
  • 28
  • 1
    This was driving me absolutely nuts until I stumbled upon your comment and surprisingly this worked.... But why? Is there a reason Android can't connect to local host? Maybe it's because of a security concern the Android OS has put in place and using ngrok provides us with a secure connection over sockets? – EsotericLanguage Jan 04 '23 at 03:59
-1

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. you can also check full documentation here https://socket.io/get-started/chat

Mustafa
  • 323
  • 2
  • 11