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)

    }


  });
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.