套接字连接超时

时间:2010-11-18 05:18:39

标签: java sockets networking timeout

在下面的代码中。

如果timout值为0(newSocket(地址,7010,0); 等待时间是“以毫秒为单位的总时间= 1024” 如果timout值为1(newSocket(地址,7010,1);  等待时间是“以毫秒为单位的总时间= 22”

是否有任何默认的操作系统设置(Windows)可以减少超时值'0'的等待时间。尝试了几个注册表项LmhostsTimeoutTcpTimedWaitDelay但没有成功。请帮我解决这个问题。


import java.net.*;
import java.io.*;

public class TestConnection
{
public static void main (String a[])
{
long t1 = System.currentTimeMillis();
          try
          {
                  InetAddress Address = InetAddress.getLocalHost();
                  System.out.println("Host Address" + Address + " Port " + 7010);
                  newSocket(Address, 7010, 0);
      long t2 = System.currentTimeMillis();
      System.out.println("SenthilTS1=" + (t2-t1));

    }catch (Exception e)
          {
     long t2 = System.currentTimeMillis();
     System.out.println("Total Time in MilliSeconds =" + (t2-t1));
     //                e.printStackTrace();
          }
}

    /*package*/ static void initSocket(Socket sock) throws SocketException {
      try {
        sock.setTcpNoDelay(true);
      } catch (SocketException se) {
        try { sock.close(); } catch (IOException ignore) {}
        //CR283953. Differentiate that the exception is thrown while doing a
        //socket set operation.
        throw se;
      }
    }

      static  Socket newSocket(InetAddress address, int port,
                            int timeout) throws IOException
    {
      Socket sock = new Socket();
      initSocket(sock);
      InetSocketAddress ina = new InetSocketAddress(address, port);
   System.out.println("******** SocketMuxer.newSocket before Socket.connect() call TimeStamp (ms)=" + System.currentTimeMillis());
   try{
    sock.connect(ina, timeout);
    System.out.println("******** SocketMuxer.newSocket after connect() SUCCESS call TimeStamp (ms)=" + System.currentTimeMillis());
   }catch (IOException e)
   {
    System.out.println("******** SocketMuxer.newSocket after connect() FAILED call TimeStamp (ms) =" + System.currentTimeMillis());
    e.printStackTrace();
    throw e;
   }
   return sock;
    }
}

1 个答案:

答案 0 :(得分:0)

默认连接超时因平台而异。大概是55-75秒,但它会有所不同。在Windows上,它由注册表项控制。你为什么要改变它?如果您正在编写代码,为什么不能总是使用正连接超时?