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

Socket.io断开连接传用户名触发Transport Error问题求助

Fixing Socket.io Transport Error When Sending Username on Disconnect

Hey there, let's walk through what's causing that transport error and how to fix it properly!

What's Going Wrong Here

The issue comes from how you're using unsubscribe() — this method is designed to stop listening to a specific Socket.io event (you'd pass an event name like 'message' to it), not to send custom data when disconnecting. When you pass an object {username: 'emons'} to unsubscribe(), it's triggering an invalid method call that breaks the transport layer connection.

Correct Approach to Send Username on Disconnect

Instead of trying to pass data through unsubscribe(), you'll want to:

  1. Send a custom event to the server with the username before disconnecting
  2. Properly close the Socket connection
  3. Clean up any event subscriptions if needed

Here's the revised client code for your ngOnDestroy method:

ngOnDestroy() {
  // Step 1: Send a custom event to notify the server the user is disconnecting
  this.connection.emit('user-disconnect', { username: 'emons' });
  
  // Step 2: Disconnect the Socket.io connection properly
  this.connection.disconnect();
  
  // Step 3: Unsubscribe from events (pass event names if you only want to stop specific ones)
  // If you want to unsubscribe all events, call without arguments:
  this.connection.unsubscribe();
}

Server-Side Handling

On the server, you'll need to listen for your custom user-disconnect event to receive the username, plus handle the default disconnect event for final cleanup:

io.on('connection', (socket) => {
  // Listen for the custom disconnect event with username
  socket.on('user-disconnect', (data) => {
    console.log(`User ${data.username} is initiating disconnect`);
    // Add your logic here: remove from connectedUsers list, update status, etc.
  });

  // Handle the final Socket disconnect event
  socket.on('disconnect', () => {
    console.log('Socket connection fully closed');
    // Optional: Fallback cleanup if needed
  });
});

Key Notes

  • Always send custom data before calling disconnect() — once the disconnect process starts, the connection might be unstable and unable to transmit data reliably.
  • unsubscribe() is for stopping event listeners, not sending data. Use emit() for sending any custom payloads to the server.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:57:20