gpt4 book ai didi

java - 写入字节数组时循环读取Socket InputStream

转载 作者:行者123 更新时间:2023-12-02 05:45:22 24 4
gpt4 key购买 nike

这是您发送文本数据时通常执行的操作

// Receiver code
while (mRun && (response = in.readLine()) != null && socket.isConnected()) {
// Do stuff
}

// Sender code
printWriter.println(mMessage);
printWriter.flush();

但是当使用 DataOutputStream#write(byte[]) 发送 byte[] 时,如何编写 while 循环来接收发送的数据。

我发现的就是这个,但它不会循环,所以我猜这只会在第一条发送的消息上运行:

int length = in.readInt();
byte[] data = new byte[length];
in.readFully(data);

我怎样才能实现这个目标?

PS:是的,我是套接字编程新手。

编辑:我每 3 到 5 秒发送一个字节数组。这就是我到目前为止所得到的。

// In the client side, in order to send byte[]. This is executed each 3 seconds.
if(out != null) {
try {
out.writeInt(encrypted.length);
out.write(encrypted);
out.writeInt(0);
out.flush();
return true;

} catch (IOException e) {
e.printStackTrace();

return false;
}
}


// In the serverside, in order to receive byte[] sent from client (also executed 3 to 5 seconds due to bytes being sent at said rate. "client" being the Socket instance.
while(true && client.isConnected()) {

byte[] data = null;

while(true) {
int length = in.readInt();
if(length == 0)
break;

data = new byte[length];
in.readFully(data);
}

if(data != null) {
String response = new String(data);

if(listener != null) {
listener.onMessageReceived(response);
}
}
}

最佳答案

假设您正在尝试处理消息流,听起来您缺少的是一种指定(在流中)消息有多大(或消息结束位置)的方法。

我建议您在每条消息之前写一个前缀,指定长度:

output.writeInt(data.length);
output.write(data);

然后在阅读时:

while (true)
{
int length = input.readInt();
byte[] buffer = new byte[length];
input.readFully(buffer, 0, length);
// Process buffer
}

需要找出一种检测输入结束的方法。据我所知,DataInputStream 没有一种干净的方法来检测这一点。有多种选择 - 最简单的可能是写出长度为 0 的消息,如果读取长度为 0,则跳出循环。

关于java - 写入字节数组时循环读取Socket InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24124996/

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