Search code examples
react-nativewebsocketsocket.ionestjssocket.io-client

Not able to use socket.io in nest js and react native ( expo )


am trying to implement a real-time functionality in my mobile app ( React native Expo ), am using NestJs as a backend and bellow is my gateway, but the connection is not happening for some reason. ( but it sais socket connected )

environment Nest Js

"@nestjs/platform-socket.io": "^8.4.5",     
"@nestjs/websockets": "^8.4.5",      
"@nestjs/common": "^9.0.0",     
"@nestjs/config": "^2.3.1",     
"@nestjs/core": "^9.0.0",

environment React Native expo

"socket.io-client": "4.7.2", 
"expo": "~48.0.11", 
"react-native": "0.71.8",

Important when i try "socket.io-client": "2.3.0" in my react native app, and i try to connect to a socket in another nestjs backend it works, the other nestJs env is (am using the same gateway):

"@nestjs/common": "^8.4.0", "@nestjs/config": "^1.2.0", "@nestjs/core": "^8.4.0", "@nestjs/platform-socket.io": "^8.4.5", "@nestjs/websockets": "^8.4.5",

my crurrent gateway :

import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from "@nestjs/websockets";

@WebSocketGateway()
export class ChatGateway {
  @WebSocketServer()
  server;

  @SubscribeMessage('message')
  handleMessage(@MessageBody() message: string): void {
    console.log("message", message);
    
    this.server.emit('message', message);
  }
}

and this is the react native screen that am testing the socket on

const ChatScreen = () => {
  const [message, setMessage] = useState("");
  const [receivedMessage, setReceivedMessage] = useState("");

  const socket = io("http://192.168.1.22:3000", {
    transports: ["websocket"],
  });

  useEffect(() => {
    socket.on("connect", () => {
      console.log("Connected to WebSocket");
    });
    socket.on("message", (message) => {
   
      setReceivedMessage(message);
    });
    // Cleanup the socket connection when the component unmounts
    return () => {
      socket.disconnect();
    };
  }, [socket]);

  const sendMessage = () => {
    try {
      socket.emit("message", message);
      setMessage("");
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View>
      <Text>Received Message: {receivedMessage} </Text>
      <TextInput
        placeholder="Enter a message"
        value={message}
        onChangeText={(text) => setMessage(text)}
      />
      <Button title="Send" onPress={sendMessage} />
    </View>
  );
};

I try it to switch version of my websocket and platform-socket.io in NestJs but it don't work, am expecting to be able to listen and emit events from both backend and the mobile app


Solution

  • It seems like SWAGGER was doing the problem, my base API endpoint is localhost:5000/api , wich is the same as the swagger documentation is, so when i removed it from there it connected with the client.