Reputation: 309
I have a problem with sockets. This:
When client-thread ends, server trying to read, and its freezes, because socket is not closed. Thread dont close it, when its over. Its problem exist, if i using thread, but if i using two independents projects, i have no problem (exception throws, and i can catch it). I cant use timeout, and i must correct continue server-work, when client dont close socket. Sorry for my bad eng.
Upvotes: 0
Views: 527
Reputation: 191
As far as I know, there is no way for TCP server (listener) to find out whether data from client are not coming because it has died/quit or is just inactive. This is not .NET's defficiency, it is how TCP works. The way I deal with it is:
1. Create a timer in my client that periodically sends signal "I am alive" to the server. For example, I just send 1 unusual ASCII character '∩' (code 239).
2. In TCP listener: use NetworkStream.Read(...)
method that allows to specify timeout. If timeout expires, the server disposes the old NetworkStream instance and creates new one on the same TCP port. If the server receives "I am alive" signal from client, it keeps listening.
By the way, the property TcpClient.Connected
is useless for detecting on server side whether client still uses the socket. The method only returns true
if last Read action returned something. So, if client is alive and just silent, the TcpClient.Connected
becomes false.
Upvotes: 4
Reputation: 171246
Close client
when you want the connection to be closed (at the end of Client
).
Better yet, use using
for all disposable resources such as both clients and the listener.
Upvotes: 2