1

I have client-server application in C#.Net and for that I am using Tcp Socket. I have used following function to aggressive close of socket object.

void CloseSocket(Socket socket)
{
      if(socket != null)
      {
           socket.ShutDown(ocketShutdown.Both);
           socket.Close();
      } 
}

In Normal Condition this function works perfectly and my method returns with 0 bytes returned from Read function.

But whenever client process terminated by taskmanager server program blocks into read function of network stream.

How can I workaround this read blocking function ? I don't want to use AsyncRead function because whole project uses blocking strategy so write now I can't change it to Async pattern.

Thanks, in advance.

4

2 回答 2

2

I'm assuming that what you are saying is that when the connection isn't closed cleanly by the client, the server can end up blocking at Read indefinitely, even if the client has actually terminated abruptly. If so: yes, that happens. So if you want to use the synchronous read methods, you should use timeouts, in particular ReceiveTimeout. If you have a multi-message protocol, it may be worthwhile adding some kind of heartbeat message periodically, to allow you to correctly identify true zombies from idle connections (for example: if you are sending a heartbeat every minute, and you haven't seen any activity on a connection for 3 minutes, hit it with a shovel).

于 2013-10-07T11:19:01.053 回答
1
**you can try this may help you**


    public void close()
        {
            if(clientSocket != null )
            {
                sendCommand("QUIT");
            }

            cleanup();

        }

    private void cleanup()
        {
            if(clientSocket!=null)
            {
                clientSocket.Close();
                clientSocket = null;
            }
            logined = false;
        }
于 2013-10-07T11:11:40.343 回答