Socket.io断开连接传用户名触发Transport Error问题求助
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:
- Send a custom event to the server with the username before disconnecting
- Properly close the Socket connection
- 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. Useemit()for sending any custom payloads to the server.
内容的提问来源于stack exchange,提问作者Sam lemonts

