Angular+RxJS WebSocket接收Node.js(ws包)后端消息显示undefined及后端open事件未触发问题
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
connectionevent fires on your WebSocket server, the client connection is already fully open—thewsinstance passed to the callback is ready to use right away. - The
openevent on an individualwsclient only applies if you're using thewslibrary 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
- Restart your Node.js server
- Refresh your Angular app
- 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
- Backend logs
内容的提问来源于stack exchange,提问作者Bogomip

