Gracie williams
Gracie williams

Reputation: 1145

Allow only one connection at a time in websocket

When someone connect to my websocket, I want the last opened connection to be active and close all other old connections. Every users has unique token. Here is the code I created:

wss.on('connection', function connection(ws,req) {

     const myURL = new URL("https://example.com"+req.url);
         var token = myURL.searchParams.get('token');
         ws.send("success");
         
      exists =  users.hasOwnProperty(token);
      if(exists)
      {
          //console.log("Token exists already");
       //   ws.send("fail");
        //  ws.close();
          users[token]["ws"].send("fail");
          users[token]["ws"].close();

         users[token] = [];
         users[token]["ws"] = ws;
         
      }
      else 
      {
            
         users[token] = [];
         users[token]["ws"] = ws;
         //console.log('connected: ' + token + ' in ' + Object.getOwnPropertyNames(users)); 
      }
          
      

 ws.on('close', function () {
    delete users[token]
    //console.log('deleted: ' + token);

             
     
 })  
      



});

But above code works only first time. If I open third time both 2nd and 3rd connection is live. I want to close the 2nd and keep the 3rd alive.

Upvotes: 0

Views: 1799

Answers (1)

srknzl
srknzl

Reputation: 787

You probably meant to use an object instead of array

so

users[token] = {};

instead of

users[token] = [];

I would close all other connections when a new connection comes so new connection handler is something like this

wss.on('connection', function connection(ws, req) {

    const myURL = new URL("https://example.com" + req.url);
    var token = myURL.searchParams.get('token');
    ws.send("success");

    exists = users.hasOwnProperty(token);

    for(const token in users){ // close all existing connections
        users[token]["ws"].send("fail");
        users[token]["ws"].close();
    }

    if (exists) {
        users[token]["ws"] = ws; // update websocket
    }
    else {
        users[token] = {ws: ws}; // add new websocket to users
        // same thing as
        // users[token] = {}
        // users[token]["ws"] = ws
    }

}

Upvotes: 1

Related Questions