Random “An existing connection was forcibly closed by the remote host.” after a TCP reset

后端 未结 4 1751
你的背包
你的背包 2021-02-19 19:14

I have two parts, a client and a server. And I try to send data (size > 5840 Bytes) from the client to the server and then the server sends the data back. I loop this a number o

4条回答
  •  余生分开走
    2021-02-19 19:36

    Two problems that I see:

    1. You are assuming that a read for size bytes will actually read size bytes. It does not. TCP is a streaming protocol. A read reads at least one byte. That's the only guarantee given.
    2. Your code will randomly deadlock. The client writes data to the server. The server echos it back. But the client will not read until it has written everything. If it writes more than the network buffers can take this will deadlock. The client must read and write concurrently. Probably, you need another thread/task for reading the data back. A good pattern to solve that issue would be to start one writer task, one reader task and to Task.WhenAll/WaitAll to join them back.

    I'm not sure under what exact circumstances a TCP stack would send a RST. Could be due to the deadlock causing a timeout.

    You are not swallowing any exceptions, right?

    Normally, closing a connection performs an orderly shutdown in the background. But I'm unsure about what happens when the other side is still writing at this point. Maybe the answer is that an RST is generated by the receiver of the writes. Surely, the TCP spec would answer this question. If this answer is to be trusted then indeed a Shutdown(Read)/Close followed by an incoming write would RST the connection.

    Fix both issues and report back with your findings.

提交回复
热议问题