I am using both methods. I wouldn't like to keep waiting to, e.g., receive and read a message in case the client disconnected. So I was wondering if I should give them a manual time out or if I can rely on this happening automatically.
Asked
Active
Viewed 23 times
0
-
Read this answer https://stackoverflow.com/a/9644780/18473608 – Jul 05 '23 at 11:31
-
I'm not sure this answers my question. I do know how to set a time out. I don't want to use a time out if ReadAsync and WriteAsync are automatically cancelled when the client disconnects. – Ungoliant Jul 05 '23 at 12:05
-
Pass a CancelationToken object as a parameter. https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.readasync?view=net-7.0 – Jul 05 '23 at 12:18
-
This also does not answer my question. I know how to use cancellation tokens. I'm specifically asking whether a disconnected client automatically cancels (and aborts) ReadAsync and WriteAsync or whether I should indeed use a timeout (and not HOW should I use a timeout or cancellation tokens). – Ungoliant Jul 05 '23 at 12:25
-
In theory, a client cannot cancel or abort when it is disconnected. Only when it decides to interrupt the stream, the server will get an IOException. So, why do you want to wait for actions/responses from a disconnected client ? Better check the IOException (and ErrorCode) or use CancelationToken. – Jul 05 '23 at 12:42
-
Let's say I am a server. Some client connected to me via tcp. I sent a welcome message to the client, and am awaiting a reply (using await NetworkStream.ReadAsync). The question is, what happens if during this time (after connecting but before replying) the client somehow disconnects. Would ReadAsync throw an exception? (If not, I would have to resort to setting a timeout.) – Ungoliant Jul 05 '23 at 12:48
-
If client closes stream, then the server will get an IOException. The docs explain what you need to know: https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.readasync?view=net-7.0 (ReadAsync) and https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.writeasync?view=net-7.0 (WriteAsync) – Jul 05 '23 at 14:25