How to get the length of the received data Socket

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_37758967/article/details/98849587

A recent item of a need to get data from the network port, then removed from the Socket and placed into byte [], the received data is not the character string
begin using byte [] buf = new byte [ 100] ; to pre-defined length, the length is too long can lead to a lot more later 0, not the length of the control.

Then from one of the Internet to find, define 100, then know the length and then redefined after reading length, but the result is not found after trying the only data, that is data

Error.

byte[] buf=new byte[100];
int len=socket.getInputStream().read(buf);
byte[] buf1=new byte[len];
socket.getInputStream().read(buf1);

Found at the end into Socket.getInputStream () Gets a stream size class which method available (), as follows:

List<InputStream> inputList = new ArrayList<InputStream>();
InputStream in = c_Socket.getInputStream();
inputList.add(in);
byte[] b = new byte[inputList.get(i).available()];
int i = inputList.get(i).read(b);

 

 

 

Guess you like

Origin blog.csdn.net/weixin_37758967/article/details/98849587