Allenxuxu / gev

🚀Gev is a lightweight, fast non-blocking TCP network library / websocket server based on Reactor mode. Support custom protocols to quickly and easily build high-performance servers.
MIT License
1.72k stars 193 forks source link

Connection closed while packet is being written to client, causing EOF (race condition) #112

Closed Sculas closed 2 years ago

Sculas commented 2 years ago

When writing to a connection and then closing the connection right after, the packet is never received on the client.

I'm trying to send an error packet and closing the connection after that, but the client never receives that packet. I'm not sure if this is a client problem, I'll have to test that soon.

Sculas commented 2 years ago

After taking a look, it seems there's a race condition on the server-side. Both the writing to and closing of the connection are sent to the event loop, but a race condition occurs where the closing happens faster or earlier while the bytes are being written. This causes an EOF error on the client because presumably, the connection was closed in the middle of receiving/writing and just cuts off.

After trying this many times, every so often the packet was fully received by the client before the connection was closed. But most of the time, the packet is cut off and causes an EOF.

Maybe, to fix this issue, we could check if something is currently writing to the out buffer and if so, wait for that to complete before closing the connection.

Sculas commented 2 years ago

Never mind, this was an issue on my end actually! When the client got an EOF, by accident, I called log.Fatal, which instantly stops the program. And well, it now makes sense why it didn't fully receive the packet ;P