Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io connection status acknowledge

I am using socket.io to build a single player/multiplayer application. Client side:

let socket = io(host,{autoConnect: false,forceNew: true});

Whenever the user press on the multiplayer option, I start connection to the server as

socket.connect();

if(socket.connected) console.log("Success")
else{
   showToast(0,"Connection Issue","Failed to connect to server")
   socket.disconnect(); 
}

The problem is socket.connected doesn't wait for the response of socket.connect() and always evaluate as false. How to wait for the response of socket.io connection request?

I tried below events but none was fired.

  1. socket.on("connect",()=>alert("Connected"));
  2. socket.on("disconnect",()=>alert("Disconnected"));
  3. socket.on("connect_error",()=>alert("Connection Error"));
like image 516
Amr Ibrahim Allam Avatar asked May 05 '26 18:05

Amr Ibrahim Allam


1 Answers

Here, I used the connect method in my previous project to get the connection event. It's working fine.

socket.on("connect",()=>alert("Connect"));

You also verify this method from the socket.io official website: https://socket.io/docs/v4/client-socket-instance/

In this case, You also need to cross-check with the server side got any connection or not. Maybe some issue with the connection between the client and server.

like image 50
Melvin Tully Avatar answered May 07 '26 08:05

Melvin Tully



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!