skip to Main Content

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"));

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @kennarddh

    socket.connect();
    socket.on("connect",()=>alert("Connected"));
    socket.on("disconnect",()=>alert("Disconnected"));
    socket.on("connect_error",()=>alert("Connection Error")); 
    

    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!


  2. // Client Side
    
    const socket = io()
    
    socket.on('connection-success', success => {
          alert('Connection');
        })
    
    
     /* Server Side */
    const express = require("express");
    const app = express();
    const io = require("socket.io")(options); // option is  HTTP server
    
    const port = 8080;
    app.get("/",(req,res)=>{
      res.send("hello world")
     });
    const server= app.listen(port, ()=>{
         console.log(`Port number ${port}`);
    });
     io.listen(server);
    
    
    io.on("connection", socket=>{
    
    
    socket.emit('connection-success',{
        status: 'connection-success',
        
    })
    socket.on("disconnect", ()=>{
        alert(`Disconnected`);
    })
    socket.on("connection_error", ()=>{
        alert(`Connection Error`);
    })
    
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search