You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+RxJS WebSocket接收Node.js(ws包)后端消息显示undefined及后端open事件未触发问题

Fixing Your RxJS WebSocket + Node.js 'ws' Communication Issues

Let's work through your two core problems step by step, with concrete fixes for both backend and frontend code:

1. Backend 'open' Event Not Triggering

The root issue here is a mismatch in how the ws package handles server-side connections:

  • When the connection event fires on your WebSocket server, the client connection is already fully open—the ws instance passed to the callback is ready to use right away.
  • The open event on an individual ws client only applies if you're using the ws library as a client (to connect to another server), not for server-side client connections.

Backend Fix:
Move your connection success log and initial message send directly into the connection callback, and add cleanup for disconnected clients:

clients = [];
wss;
webSocketServer() {
  this.wss = new WebSocket.Server({ port: 7072 });
  this.wss.on('connection', (ws) => {
    const id = methods.generateRandomId(5);
    this.clients.push({socket: ws, data: { id }});
    // Move this logic out of the non-firing 'open' event
    console.log(`Client ${id} has connected.`)
    this.sendWebsockMessage(`User ${id} connected...`);

    ws.on('message', (msg) => {
      const message = JSON.parse(msg);
      console.log(message);
    });
    ws.on('close', () => {
      console.log(`Client ${id} has disconnected.`)
      // Clean up the clients array to avoid dead sockets
      this.clients = this.clients.filter(client => client.data.id !== id);
    })
  })
}
sendWebsockMessage(msg) {
  // Send valid JSON instead of invalid template string syntax
  const payload = JSON.stringify({ content: msg });
  this.clients.forEach(client =>{
    client.socket.send(payload);
  });
}

2. Frontend Receiving 'undefined' Messages

Your custom deserializer: () => {} is breaking message parsing—this function is supposed to return the processed message data, but your empty implementation returns undefined. Additionally, your backend was sending invalid JSON (unquoted keys like hello aren't allowed), which would cause parsing failures even if the deserializer worked.

Frontend Fix:
Remove the empty deserializer (RxJS handles JSON parsing by default) and adjust your subscription to handle valid JSON:

ws: WebSocketSubject<any>;
webSockets(): void {
  // Remove the broken deserializer—RxJS parses JSON automatically
  this.ws = webSocket({url: `${environment.websocketUrl}`});
  
  this.ws.subscribe(
    {
      next: (message: any) => {
        // Now you'll get the properly parsed JSON object
        console.log(`Received message:`, message);
      },
      error: (error) => {
        console.log(`Socket error: ${error}`);
      },
      complete: () => {
        console.log("Connection to server closed");
      }
    });
}
sendTestMessage(): void {
  // Send stringified JSON to match your backend's JSON.parse usage
  this.ws.next(JSON.stringify({ msg: 'hello' }));
}

Verify the Fixes

  1. Restart your Node.js server
  2. Refresh your Angular app
  3. You should now see:
    • Backend logs Client [id] has connected. when a client joins
    • Frontend logs actual message objects instead of undefined
    • Frontend-to-backend messages continue working as expected

内容的提问来源于stack exchange,提问作者Bogomip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:28:12