gpt4 book ai didi

java - 字节数组读取

转载 作者:行者123 更新时间:2023-12-01 13:04:57 26 4
gpt4 key购买 nike

我在从客户端向服务器写入和读取字节数组时遇到问题。客户端实际上写入了所有字节,但服务器似乎无法读取它。这是客户端和服务器端的代码

Socket sock = new Socket(Interface.SERVER_IP, 4444);
PrintStream os = new PrintStream(sock.getOutputStream());

os.println("3");
DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());

dOut.writeInt(data.length); // byte array created above
dOut.write(data);

服务器端是:

DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
int length = clientData.readInt();
System.out.println(length);
byte[] data = new byte[length]; // read length of incoming message
if(length>0) {
clientData.readFully(data, 0, data.length); // read the message
}

服务器似乎被阻塞在读取字节数组长度的行上。请我真的需要帮助解决这个问题

最佳答案

写入数据后,刷新输出:

        dOut.writeInt(data.length); // byte array created above
dOut.write(data);
dOut.flush();

或者,关闭流(如果您不打算再次使用它)...

        dOut.writeInt(data.length); // byte array created above
dOut.write(data);
dOut.close();

另请注意,您的 PrintWriter 正在打印字符串值(“3”)。您正在将额外的数据打印到流中,但这些数据似乎并未在服务器上消耗。

关于java - 字节数组读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23336750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com