Socket io in React Native

Viewed 7021

I am using Socket.io for my react-native project. The nodejs server is hosted with Heroku. When I tried to connect from the app to server, it works perfectly !! But when try I emit a message, I can't see it on my receiving Reactjs site
Here's the code for react native app ->

import { io } from "socket.io-client";

useEffect(() => {
if (tried === true) {
  const socket = io("wss://my-domain-name.herokuapp.com");

  socket.emit("finishPayment", "true");

  setScanned(false);
}
}, [status]);

Here's the receiving client side code (React js) ->

socket.on("finishPayment", (msg) => {
  console.log(msg);
});

The connection is done (in the app), but the message is not emitted.
Any idea why is this happening ?
Thanks !

3 Answers

I solved it !!! Here's the final code ->

import { Text, View, StyleSheet, Alert } from "react-native";

navigator.__defineGetter__("userAgent", function () {   // you have to import rect native first !!
 return "react-native";
}); 

import SocketIOClient from "socket.io-client/dist/socket.io.js";
 
  //

  useEffect(() => {
const socket = SocketIOClient("wss://site-name.herokuapp.com/", {
  jsonp: false,
});
socket.on("connect", () => {
  console.log("connected");
  socket.emit("hello", "world");
});

socket.on("connect_error", (err) => {
  console.log(err instanceof Error);
  console.log(err.message); 
});
}, []);

On android (locally) the problem for me was that I did not open the connection between mi socket serve and react native app. Just run adb reverse tcp:3000 tcp:3000 on the terminal and the server ports will be opened for connection. I use 3000 for my server but change it to your server's port locally.

adb reverse tcp:3000 tcp:3000

this is much cleaner.

 const io = require('socket.io-client/dist/socket.io');

 const socket = io(
    `API URL`,
    {
      transports: ['websocket'], // you need to explicitly tell it to use websockets
    },
  );

  socket.on('connect', () => {
    console.log('connected --------------- socket ---------------');
  });

  socket.on('connect_error', err => {
    console.log(err.message);
  });
Related