gpt4 book ai didi

Java Socket Inputstream 读取错误数据

转载 作者:行者123 更新时间:2023-11-29 05:38:25 27 4
gpt4 key购买 nike

谁能告诉我这段代码有什么问题,我所做的就是这样

  1. 客户端发送图像数据,是来自c++的uchar数组。
  2. Java 服务器使用服务器套接字接收此数据并将其存储为字节数组。

这是代码...

   private ServerSocket serverSocket;
InputStream in;
int imageSize=300;//921600;//expected image size 640X480X3
public imageReciver(int port) throws IOException {
serverSocket = new ServerSocket(port);
}


Socket server = null;
server = serverSocket.accept();
in = server.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[100];

int remainingBytes = imageSize; //
while (remainingBytes > 0) {
int bytesRead = in.read(buffer);
if (bytesRead < 0) {
throw new IOException("Unexpected end of data");
}
baos.write(buffer, 0, bytesRead);
remainingBytes -= bytesRead;
}
in.close();

byte imageByte[] = new byte[imageSize];
imageByte = baos.toByteArray();
baos.close();

inputstream in 读取时,我在 buffer 上得到负值。

最佳答案

我认为问题是:

Java 的字节是有符号的,而您发送的是无符号字节。

来自 Java docs :

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

你可以试试这样的:

short bVal = /*signed byte*/;
if (bVal < 0)
bVal = bVal + 256; //Convert to positive

编辑: 正如@Aubin 所指出的,short 将是更好的选择,而不是 int。

关于Java Socket Inputstream 读取错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628886/

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