Java - 如何从inputStream(socket / socketServer)读取未知数量的字节? [英] Java -- How to read an unknown number of bytes from an inputStream (socket/socketServer)?

查看:272
本文介绍了Java - 如何从inputStream(socket / socketServer)读取未知数量的字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望使用inputStream读取套接字上的某些字节。服务器发送的字节可以是可变数量的,并且客户端事先不知道字节数组的长度。如何实现?

Looking to read in some bytes over a socket using an inputStream. The bytes sent by the server may be of variable quantity, and the client doesn't know in advance the length of the byte array. How may this be accomplished?


byte b[]; 
sock.getInputStream().read(b);

这会导致Net BzEAnSZ出现可能未初始化错误。帮助。

This causes a 'might not be initialized error' from the Net BzEAnSZ. Help.

推荐答案

读取一个int,它是接收的下一个数据段的大小。创建具有该大小的缓冲区,或使用宽敞的预先存在的缓冲区。读入缓冲区,确保它仅限于上述大小。冲洗并重复:)

Read an int, which is the size of the next segment of data being received. Create a buffer with that size, or use a roomy pre-existing buffer. Read into the buffer, making sure it is limited to the aforeread size. Rinse and repeat :)

如果确实未按照您的说法提前知道大小,请阅读扩展的ByteArrayOutputStream作为另一个答案已经提到了。但是,尺寸方法确实是最可靠的。

If you really don't know the size in advance as you said, read into an expanding ByteArrayOutputStream as the other answers have mentioned. However, the size method really is the most reliable.

这篇关于Java - 如何从inputStream(socket / socketServer)读取未知数量的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆