admin管理员组

文章数量:814911

如何将额外的数据附加到WebSocket连接,以便在断开连接时可以进行清理

我使用此实现将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) { ....

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

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

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

回答如下:

也许您没有意识到,但是在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
  });
});

本文标签: 如何将额外的数据附加到WebSocket连接,以便在断开连接时可以进行清理