用socket写的异步收发的tcpserver,求能及时判断连接的中断的方法,包括客户端的非正常退出。
或者说在异步发送数据前能否判断连接是否已断开,要实时的。
主要是在实际使用时发现,当正在向多个client异步高速发送数据时,如遇多个连接同时关闭,会导致程序自动退出,有时用try也捕获不到,求解决办法。

解决方案 »

  1.   


    // .Connect throws an exception if unsuccessful
    client.Connect(anEndPoint);// This is how you can determine whether a socket is still connected.
    bool blockingState = client.Blocking;
    try
    {
        byte [] tmp = new byte[1];    client.Blocking = false;
        client.Send(tmp, 0, 0);
        Console.WriteLine("Connected!");
    }
    catch (SocketException e) 
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
            Console.WriteLine("Still Connected, but the Send would block");
        else
        {
            Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
        }
    }
    finally
    {
        client.Blocking = blockingState;
    } Console.WriteLine("Connected: {0}", client.Connected);CSDN上这样说的,我觉得每次发送前要处理一次异常,系统开销比较大。可是还没有找到更好的办法
      

  2.   

    Socket.Available属性
    timer
    if (socket.Poll(100, SelectMode.SelectRead)){}
      

  3.   

    仔细查了下,好像是存客户端端口的链表没有lock,不报错直接退出,查起问题来太痛苦了
      

  4.   

    TCP的断线问题,一直是很难处理的问题
    大部分用try/catch来捕捉,再多试试啰!