我测试了一下 ,如果对方主机不存在的话,超时时间为:21s左右,我想把它改小一点,但不知道怎么改?

解决方案 »

  1.   

    帮你顶,好像我以前设置了socket的timeout什么的不管用
      

  2.   

    1、在连接前,启动一个timer,timer的时间就是连接关闭的时间
    2、如果连接成功,则停用timer,成功
    3、如果连接不成功,在timer事件中调用socket.close()方法
    4、socket.connect的功能会报错,缉获并处理这个错误
      

  3.   

    下面是一个异步socket典型的连接程序
    connectDone 是ManualResetEvent类型可以在connectDone.WaitOne();
    中使用等待的时间来限制连接超时
    比如connectDone.WaitOne(5000);
    是超时时间为5秒
    connectDone.WaitOne();
    public void Conn()
    {
    try
    {
    ClientSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    IPAddress ipAddress = IPAddress.Parse(tcpIpServerIP);
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, tcpIpServerPort);
    connectDone.Reset();
    ClientSocket.BeginConnect(remoteEP,new AsyncCallback(ConnectCallback),ClientSocket);
    connectDone.WaitOne();
    StateObject state = new StateObject(bufferSize,ClientSocket);
    ClientSocket.BeginReceive(state.buffer,0,bufferSize,0,
    new AsyncCallback(ReceiveCallback), state);
    }
    catch(Exception e)
    {
    OnErrorEvent(new ErrorEventArgs(e));
    }

    }
      

  4.   

    具体可参考
    http://blog.csdn.net/zhiang75/archive/2004/08/16/75915.aspx