有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果服务器超时,javasocketInputStream read()是否会解除阻止?

我有一个服务器,如果没有收到完整的请求,它会在45秒后超时并关闭连接。我通过Socket连接到此服务器,并将请求写入socket的OutputStream

Socket socket = new Socket("myhost", myPort);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.write(properRequestMessage);
out.flush();

我在这里假设我的请求是好的(遵循我的协议)。服务器应该用一个文件进行响应。我尝试从socket inputstream读取:

BufferedReader response = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String in;

while((in = response.readLine()) != null) {
    System.out.println(in);
}

这里的readLine()阻塞,我认为这是因为我的服务器认为我的请求没有正确终止,因此正在等待更多

现在,如果45秒过去,我的服务器超时,readLine()会解锁还是等待一些Socket默认超时时间


共 (3) 个答案

  1. # 1 楼答案

    这取决于服务器超时时做什么。如果它关闭了连接,你就会看到。如果它只是记录了一条消息,你可能什么也看不到

    没有默认的读取超时。您的readLine()可以永远等待

  2. # 2 楼答案

    readLine()方法将阻塞,直到它接收到输入或直到底层套接字read()超时结束。 您没有在read命令上设置超时,而是在socket上设置超时

    Socket.setSoTimeout(int ms)

    Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

    实际发生的情况还取决于服务器的操作,如果服务器正确关闭套接字,IOException应该抛出一个readLine()。如果连接未关闭,它将等待套接字超时

  3. # 3 楼答案

    如果服务器在超时时关闭其套接字的末端,那么^{}将返回null