Java DataInputStream 读取不return

Java DataInputStream read does not return

我正在实现一个简单的 client/server reader 并且我正在使用 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 没有 return。

套接字将阻塞,直到没有更多输入为止。 InputStream 只是一个接口,具体行为取决于它的提供者实现。在您的套接字上设置超时,以便在一定时间内没有输入时抛出异常。

这里引用 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 之外,还可以。在套接字上设置超时并确保正确处理抛出的异常。