Java TCP Socket没有超时(在Servlet中调用)

时间:2013-07-04 11:29:07

标签: java sockets servlets tcp

美好的一天,

我有一个Java Servlet,我实际上需要发送TCP数据包。如果连接打开,我可以成功发送数据..

但是,如果它确实需要超时,它永远不会。

我的套接字发送代码如下:

private static String sendMessage(int command,String data,int port,String ip){
    try{
        String sendString=Integer.toString(command)+":"+data+'$'+'\n';
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
        Socket clientSocket = new Socket(ip, port);
        clientSocket.setSoTimeout(30000);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outToServer.writeBytes(sendString);
        String rcvString = inFromServer.readLine();
        System.out.println("FROM DEVICE: " + rcvString);
        clientSocket.close();
        return rcvString;
    }catch(Exception e){
        System.err.println(e.getMessage());
    }

    return NULL;
}

如您所见,我将超时设置为30秒。但是,超时需要将近80秒。有时需要60秒。它不断变化。我将超时设置为10秒,但仍然需要很长时间。好像这个功能根本不起作用。是什么赋予了!?这是一个线程问题吗?

1 个答案:

答案 0 :(得分:0)

您正在设置连接后的超时。

试试这个:

 private static String sendMessage(int command,String data,int port,String ip){
     try{
         String sendString=Integer.toString(command)+":"+data+'$'+'\n';
         BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

         // Socket clientSocket = new Socket(ip, port);
         // clientSocket.setSoTimeout(30000);

         Socket clientSocket = new Socket();
         InetAddress addr = InetAddress.getByName(ip);
         SocketAddress sockaddr = new InetSocketAddress(addr, port);
         clientSocket.connect(sockaddr, 20000); // 20 seconds time out

         DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
         BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         outToServer.writeBytes(sendString);
         String rcvString = inFromServer.readLine();
         System.out.println("FROM DEVICE: " + rcvString);
         clientSocket.close();
         return rcvString;
     }catch(Exception e){
         System.err.println(e.getMessage());
     }

     return NULL;
 }