簡體   English   中英

如何在 node.js 應用程序中使用 fastify-ws 向所有連接的 sockets 發送 http 響應?

[英]How to send http responses to all the connected sockets with fastify-ws in node.js application?

我在 node.js 應用程序中為 WebSocket 使用“fastify-ws”。 我也在同一個端口中使用 HTTP 通信。 我必須通過 WebSocket 將 HTTP 響應發送到連接的 sockets。

這是我的示例代碼:

var connectedSockets = [];

function socketConnect(socket, req) {
  console.log('Client connected');
  connectedSockets.push(socket);

  socket.on('close', () => {
    console.log('websocket closed');
    connectedSockets = connectedSockets.filter((sk) => sk !== socket);
    });
}

module.exports = { connectedSockets, socketConnect };

如果連接了任何客戶端,我會將套接字推送到 connectedSockets 數組中,並在關閉時從數組中刪除特定的套接字。 然后我將通過另一個文件中的 WebSockets 發送 HTTP 響應如下。

const { connectedSockets } = require('../controllers');

// inside response

connectedSockets.forEach((socket) => {
            socket.send(JSON.stringify(response));
        });

通過這樣做,可以連接客戶端。 我可以成功發送回復。 如果連接了多個客戶端並且關閉了一個客戶端,則會在發送響應時引發類似“WebSocket 未打開就緒狀態 3 (CLOSED)”的錯誤。 問題是斷開連接的套接字 object 仍在 connectedSockets 數組中,並且它具有屬性 _closedFrameReceived: true。

您的腳本的問題是您有 2 個文件:

  • 帶有指向數組的connectedSockets的文件 A

  • 文件 B 的connectedSockets指向文件 A 的connectedSockets

當你這樣做

connectedSockets = connectedSockets.filter((sk) => sk !== socket);

您僅更改文件 A 的connectedSockets指針,而文件 B 指針未更新,它鏈接舊數組。

您應該像這樣更改數組:

const index = connectedSockets.findIndex((sk) => sk === socket);
if (index > -1) {
  connectedSockets.splice(index, 1);
}

或者更新文件 B 中的 var。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM