简体   繁体   中英

NetworkStream.Read still blocks even when network goes down

I have a server and multiple clients which connect via TCP sockets. The server listens for connecting clients which first register themselves using their unique device id. When the device first registers, the server then 'prods' the client with a small message. This wakes up the client into downloading data from another source.

The problem we are having is that the network is over GPRS and quite often in poor coverage areas the network goes down or the quality of service is poor. What seems to be happening is that inside the client, the NetworkStream.Read() call is blocking even when the network layer drops. There is no exception thrown and even when the network returns, the call seems to then not detect any data.

Is there any reason for this? How do I get round this issue?

I would have thought the NetworkStream would at least throw an exception so the client can go into a retry connect stage.

NetworkStream does not detect connectivity between one client and another. It just listens for data. Read() blocks the thread until it receives data.

Instead, consider using BeginRead (or ReadAsync in .Net 4.5). It won't block the thread and, after a timeout with no new data, you can close the socket, create a new one and start again.

What you need is a read timeout. It is possible in some circumstance for a TCP read to block forever even if the peer isn't running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM