Fastify WebSocket -如何获取当前连接的客户端?

dgenwo3n  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在尝试让当前用户连接到WebSocket服务器。
这是我的代码注册WebSocket

fastify.register(FastifyWebsocket, {
  options: {
    clientTracking: true
  }
});

字符串
设置fastify连接

fastify.get(
    "/websocket",
    { websocket: true },
    (connection /* SocketStream */, req /* FastifyRequest */) => {
      const userToken = req.query?.userToken || req.request?.query?.userToken;
      if (userToken) {
        const userId = userIdToken(userToken);
        // Store the user ID in the connection context
        connection.socket.userId = userId;
      }

      connection.socket.on("message", (message) => {
        console.log("Web Socket - message", parseMessage(message));
      });
    }
  );


然后我有一个发送通知的功能

/**
 * Sends a WebSocket notification to all connected clients.
 * @param {Object} payload - The payload to send as a WebSocket notification.
 * @param {String} type - The type of notification to send.
 */
export const sendGeneralNotification = function (type, payload) {
  fastify.websocketServer.clients.forEach((client) => {
    client.send(JSON.stringify({ type, payload }));
  });
};


我的问题是“fastify.websocketServer.clients”总是设置为(0),即使有客户端连接到服务器。
如何让当前客户端连接到服务器?
fastify版本:^4.18.0
@fastify/WebSocket:^7.2.0

muk1a3rh

muk1a3rh1#

我认为问题是propieta客户端不存在于@fastify/WebSocket中作为websocketServer对象的一部分,如您所见:https://github.com/fastify/fastify-websocket我做些测试再告诉你在我看来,这就是问题所在。
对不起,我的回答是支离破碎的。使用连接事件连接的客户端。

const connectedClients = new Set();

// Register the event handler for the "connection" event
fastify.websocketServer.on("connection", (client) => {
  connectedClients.add(client);
   
});

// Function to send a WebSocket notification to all connected clients
export const sendGeneralNotification = function (type, payload) {
  connectedClients.forEach((client) => {
    client.send(JSON.stringify({ type, payload }));
  });
};

字符串

相关问题