Socket inputStream 读取消息给出意外的长度

问题描述 投票:0回答:1

我有一个从客户端读取消息的函数,超时时间为 100 毫秒。在我的代码中,我在循环中使用这个函数,直到得到一个与“”不同的字符串,这就是我知道我得到了我需要的消息并可以继续我的代码的方式。由于某种原因,它适用于第一个套接字,但是当我将从套接字接收到的内容发送到套接字 2 并等待套接字 2 响应时,即使套接字 2 仍然连接并处于活动状态,我也会得到 bytesReceived = -1。

代码:

public String getMessage(int socketNumber) {
    Socket socket = socket1;
    if(socketNumber == 2){
        socket = socket2;
    }
    byte[] message = new byte[4096];
    int bytesReceived = 0;

    try {
        socket.setSoTimeout(100);
        bytesReceived = socket.getInputStream().read(message);
    } catch (SocketTimeoutException e) {
        return "";
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    System.out.println("AMOUNT OF BYTES RECEIVED FROM" + socketNumber + " IS " + bytesReceived);
    // Convert the message to a string.
    return new String(message, 0, bytesReceived);
}
java sockets networking serversocket
1个回答
-1
投票

你应该做类似的事情

try (InputStream in = socket.getInputStream()) {
   StringBuilder builder = new StringBuilder();
   byte[] buffer = new byte[4096];
   int count;
   while ((count = in.read(buffer) > 0) {
      builder.append(new String(buffer, 0, count));
   }
   return builder.toString();
}
© www.soinside.com 2019 - 2024. All rights reserved.