我正在读取用于显示图像的 TCP 数据包
。每个数据包的长度应为 1025
。每次,我都会得到 128 行,然后绘制图像。
所以我首先初始化
s = new Socket(ip, port);
stream = s.getInputStream();
byte[] tmpBuffer = new byte[1025];
byte[] finalBuffer = new byte[128 * 1025];
int count_lines =0
然后我逐流读取长度为1025的流,
while((read = stream.read(tmpBuffer, 0, tmpBuffer.length)) != -1){
System.arraycopy(tmpBuffer, 1, finalBuffer, count_lines * 1025, 1025);
count_lines++;
if(count_lines == 128) break;
}
问题是当我记录read
整数时,我得到一堆1025
,但有时(显然是随机的)423
或602
(注意到423+602=1025
)
我的TCP
读取有问题还是服务器端有问题?
最佳答案
Am I going wrong with the TCP reading or is there a problem on the server side ?
在 TCP 中,只有字节流。您拥有消息,也无法控制数据包,这些数据包的长度通常不超过 1532 字节。
您必须有自己的协议(protocol)来处理消息的发送。
inputStream.read(buffer)
将读取 1 个字节和 buffer.length
之间的数据,并且您不能忽略正在读取的实际长度。
如果你想读入已知长度的缓冲区,你可以使用
DataInputStream dis = new DataInputStream(socket.getInputStream());
byte[] finalBuffer = new byte[128 * 1025];
dis.readFully(finalBuffer);
readFully
一次读取尽可能多的内容,直到完全读取 byte[]
。
更灵活的协议(protocol)是先发送长度。
public static void write(DataOutputStream out, byte[] bytes) {
out.writeInt(bytes.length());
out.write(bytes);
}
public static byte[] read(DataInputStream in) {
int length = in.readInt();
byte[] bytes = new byte[length];
in.readFully(bytes);
return bytes;
}
这样,无论您发送的数据长度如何,您都会以相同的方式接收。
关于java - 在java中读取TCP问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36102650/