Canceling TcpClient after TcpListener has been stopped
So, I may have done this completely right, but I'm a bit unsure on the behavior. I'm creating TcpClients with
AcceptTcpClientAsync
and passing it a CancellationToken
which does seem to end the TcpClients, but I guess I'm expecting to see a more graceful end in my TcpCleints which I am not.
To wit, I'm expecting to end up hitting client.Close
and then get the "Client disconnected" message, which isn't happening.28 Replies
If you're looking for a graceful end. You need to call
.disconnect()
first before closing.Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
If you cancel first. It's gonna throw a
System.OperationCancelled
exception.Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
graceful end isn't the right word yeah.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
but yeah I guess I need to wrap it. I'll try that.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
That's a server setup.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
Oh yeah I only just noticed that yeh. That'll definitely be an issue
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
hmm, no point in catching the exception really, I have nothing to do with it. I'll just put in a finally.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
it's fine for this.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
I mean, this is just an echo service. There isn't any way I can "gracefully" tell the client "I'm not going to handle your requests anymore"
It depends on what exceptions are too sometimes. Usually something with a SocketException is an ungraceful disconnect e.g. timeouts and connection resets. With OperationCancelledException. You might want to gracefully disconnect before closing.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
I can call
client.Stop
in the finally
That'll just completely throw a SocketException on the client side.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
no particular reason, I just don't really have anything to do with the exception here.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
the exception isn't bubling out of here.
Unknown User•8mo ago
Message Not Public
Sign In & Join Server To View
ahhhh I know why. But that's okay as well.
hmm...
finally
does let me avoid some code duplication (catch path isn't taken on a normal client exit). But hmm... maybe I'll look into just registering some cleanup methods in the token instead.