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.
- socket.on("connect",()=>alert("Connected"));
- socket.on("disconnect",()=>alert("Disconnected"));
- socket.on("connect_error",()=>alert("Connection Error"));
2
Answers
Thanks to @kennarddh
Appreantly using socket.connected doesn't wait for the reponse. registering event using socket.on to be called on the status of the request worked!