0

再会,

我有一个 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 秒。有时需要60s。它不断变化。我将超时设置为 10 秒,但仍然需要很长时间。就好像该功能根本不起作用。是什么赋予了!?是线程问题吗?

4

1 回答 1

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;
 }
于 2013-07-04T12:15:30.550 回答