【问题标题】:How to attach extra data to a WebSocket connection so I can do clean up on disconnect如何将额外数据附加到 WebSocket 连接,以便我可以在断开连接时进行清理
【发布时间】:2020-05-09 13:11:08
【问题描述】:

我正在使用 npm ws 作为我的 WebSocket 服务器,并使用此实现:

const fs = require("fs");
const https = require("https");
const WebSocket = require("ws");

const server = https.createServer({
  cert: fs.readFileSync("./cert.pem"),
  key: fs.readFileSync("./key.pem"),
});
const wss = new WebSocket.Server({ server, clientTracking: true });

这是我的听众:

wss.on("connection", function connection(ws) {
  console.log("connection");

  ws.on("close", function close(ws) {
    console.log("disconnect");
  });

  ws.on("message", function incoming(message) {
    console.log("INBOUND MESSAGE: %s", message);
    obj = JSON.parse(message);

    switch (obj.action) { ....

我正在使用套接字服务器来设置纸牌游戏。我可以将来自on("messagews 连接附加到一个对象(例如player[id].ws = ws),并且我可以使用该附加数据发送消息(例如ws.send(player[id].ws, ____);

我面临的挑战是当连接断开时,我需要清理玩家周围的所有游戏数据(游戏数据、玩家数据等)。但是,当"close" 侦听器触发时,ws 数据中没有任何数据,因此我可以识别谁丢弃并清理数据?

我希望能够将on("message" 设置为ws.playerId='ksjfej,所以当我得到ws("close" 时,我可以使用ws.playerId 进行清理。

【问题讨论】:

    标签: node.js websocket ws


    【解决方案1】:

    也许您没有意识到,但在close 事件中,表示连接的ws 变量完全在范围内,只要您从回调中删除错误声明的ws 参数。所以,这会奏效。

    wss.on("connection", function connection(ws) {
      console.log("connection");
    
      // change this callback signature to remove the `ws`
      ws.on("close", function(/* no ws here */) {
        console.log("disconnect");
        // you can reference the `ws` variable from a higher scope here
        // you just have to remove it from the function parameter list here
        // because it isn't passed to the event itself.
        console.log(ws);   // this will get ws from the higher scope
      });
    });
    

    【讨论】:

    • 谢谢!这非常有效,我在连接时分配了playerId,我可以清理"close" 上的所有其他内容。我想知道为什么在npm ws 文档中他们重新声明ws 而不是让它通过。无论如何,谢谢friend00!
    • @WilWells - 我看不到 npm ws 文档在哪里将 ws 重新声明为关闭事件参数。我不确定你在哪里看到的。
    • 你是对的。我一定是在构建它时打错了它。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2021-06-23
    • 2016-08-21
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    相关资源
    最近更新 更多