Socket.IO Node.js应用TCP连接测试:发消息即断开问题求助
Hey there! Let's dig into why your Socket.IO connection closes right after sending a message via telnet. The core issue here is that Socket.IO isn't a raw TCP protocol—it has its own layered handshake rules and message formatting standards that plain telnet doesn't adhere to by default. Here's how to diagnose and fix this:
1. Why the Connection Drops Immediately
When you send plain text through telnet, the Socket.IO server can't parse your input against its protocol specifications. It sees invalid, unstructured data and terminates the connection right away to avoid unexpected errors. Socket.IO requires a specific handshake process first, plus standardized message framing for all data exchanged.
2. Step-by-Step Fix to Test with Telnet
Follow these exact steps to properly communicate with your Socket.IO server using telnet:
a. Complete the Socket.IO WebSocket Handshake
First, you need to upgrade the TCP connection to WebSocket (Socket.IO's default transport). Start by connecting via telnet:
telnet your-server-ip your-server-port
Then paste this HTTP request (replace your-server-host:port with your actual server details):
GET /socket.io/?EIO=4&transport=websocket HTTP/1.1 Host: your-server-host:port Connection: Upgrade Upgrade: websocket Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13
(Don't forget the blank line at the end—it signals to the server that the request is complete.)
If the handshake succeeds, you'll receive a 101 Switching Protocols response from the server.
b. Send Valid Socket.IO Formatted Messages
Once the handshake is done, all messages must follow Socket.IO's framing rules:
- To send an event-based message, use the prefix
42(denotes an event payload) followed by a JSON array of the event name and content:42["chat", "Hello from telnet!"] - For plain text messages (no attached event), use the prefix
4instead:4"Simple plain text message"
3. Additional Checks to Rule Out Other Issues
- Confirm your Socket.IO server has WebSocket transport enabled (it's on by default, but double-check if you've modified server configs).
- Ensure there's no server-side middleware or validation logic that rejects unformatted messages.
- Check if your server has overly strict timeout settings—though in your case, the connection closes immediately after sending, so this is less likely to be the cause.
4. Easier Alternative Testing Tools
If telnet feels too cumbersome for Socket.IO testing, try wscat (a dedicated WebSocket client) which handles the handshake automatically:
wscat -c ws://your-server-ip:port/socket.io/?EIO=4&transport=websocket
You can then send Socket.IO-formatted messages directly without dealing with raw HTTP handshake steps.
内容的提问来源于stack exchange,提问作者jdog

