我正在实现一个简单的客户端/服务器读取器,并使用 DataInputStream 将所有内容读取为字节,然后稍后进行解析。
这是我的阅读代码:
String line;
String requestString = "";
//client is a Socket that is initialized elsewhere
DataInputStream inputData = new DataInputStream(client.getInputStream());
byte [] messageByte = new byte[1024];
int counter = 0;
while(true) {
int bytesRead = inputData.read(messageByte, counter, 1024-counter);
counter = (counter + bytesRead)%1024;
if(bytesRead == -1) {
System.out.println("Breaking out of loop");
break;
}
line = new String(messageByte, 0, bytesRead);
System.out.println( "GOT > " + line );
}
它能够读取消息,但无法跳出循环,因为最后一次调用 read 没有返回。
最佳答案
套接字将阻塞,直到没有更多输入。 InputStream 只是一个接口(interface),确切的行为取决于其提供者的实现。在您的套接字上设置超时,以便在一段时间内没有输入时抛出异常。
这里引用自 javadoc on Socket ,请注意,它将从套接字读取的行为描述为阻塞操作,直到达到超时:
public void setSoTimeout(int timeout) throws SocketException
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.
解决办法:
除了检查 -1 之外,这是可以的。在套接字上设置超时并确保抛出的异常得到正确处理。
关于Java DataInputStream 读取不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52339611/