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

编程入门 行业动态 更新时间:2024-10-12 12:25:18

<a href=https://www.elefans.com/category/jswz/34/1771359.html style=如何将额外的数据附加到WebSocket连接,以便在断开连接时可以进行清理"/>

如何将额外的数据附加到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连接,以便在断开连接时可以进行清理

本文发布于:2024-05-07 08:44:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755452.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   数据   WebSocket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!