【问题标题】:Java Socket: how to skip reading line from server when no output is sent from the serverJava Socket:当服务器没有发送输出时如何跳过服务器的读取行
【发布时间】:2014-03-08 05:53:33
【问题描述】:

所以我有这个 Java TCP 套接字客户端应用程序。很简单:

public class Main {

    public static void main(String argv[]) throws Exception {
        String hostName = "localhost";
        int portNumber = 5000;

        Socket echoSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        String userInput;
        while ((userInput = stdIn.readLine()) != null) {
            out.println(userInput);
            System.out.println("echo: " + in.readLine());
        }
        echoSocket.close();
    }
}

现在您可以在 while 循环中看到,当用户输入内容时。它被发送到服务器。然后客户端等待对服务器的响应。如果服务器只是回显客户端输入的内容,那么这非常有效!
“但是”当服务器没有任何响应时,我的程序只是挂起......永远等待来自服务器的输入。

所以我的问题是,如何修改代码,以便在服务器没有返回任何内容时,它不会停止?
我必须使用线程吗? 1从读取和发送客户端输入,另一个从服务器打印出响应?

【问题讨论】:

    标签: java sockets tcpclient


    【解决方案1】:

    您可以在套接字上使用setSoTimeout()

    Socket echoSocket = new Socket(hostName, portNumber);
    echoSocket.setSoTimeout(10000); // Readings are timeouting after 10 seconds
    

    来自 javadoc:

    使用指定的超时启用/禁用 SO_TIMEOUT,以毫秒为单位。将此选项设置为非零超时,与此 Socket 关联的 InputStream 上的 read() 调用将仅阻塞此时间量。如果超时到期,则会引发 java.net.SocketTimeoutException,尽管 Socket 仍然有效。 必须在进入阻止操作之前启用该选项才能生效。超时必须 > 0。超时为零被解释为无限超时。

    参数:

    timeout指定的超时时间,以毫秒为单位。

    因此,当您阅读该行时,您可以这样做:

    try {
        System.out.println("echo: " + in.readLine());
    } catch (SocketTimeoutException ste) {
        // Do something
        System.out.println("nothing received");
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多