简体   繁体   English

在 websocket 中一次只允许一个连接

[英]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.Following is the code I created当有人连接到我的 websocket 时,我希望最后打开的连接处于活动状态并关闭所有其他旧连接。每个用户都有唯一的令牌。以下是我创建的代码

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.Any help is appreciated Thank you.但是上面的代码只在第一次工作,如果我第三次打开第二次和第三次连接都是活动的。我想关闭第二次并保持第三次活动。感谢任何帮助谢谢。

You probably meant to use an object instead of array您可能打算使用 object 而不是数组

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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM