Java TCP How do you read a sent stream size (header) and keep reading based upon that size

妖精的绣舞 提交于 2019-12-12 06:59:26

问题


Given the following pseudo code. how would I do read in the given data


回答1:


Use DataInputStream to make your life easy.

DataInputStream in = new DataInputStream(socket.getInputStream());
short myShortStreamSize = in.readShort();
byte[] payload = new byte[myShortStreamSize];
in.readFully(payload);



回答2:


Socket has a getInputStream() method. You would use the returned InputStream and read myShortStreamSize of bytes from it into a byte[], convert that into a int/long representing your payload size and then read into another, larger, new byte[payloadSize], the payload itself.




回答3:


You can try JBBP

@Bin class Struct { byte [] payload; }
@Bin class ParsedStream { Struct [] structs; }
ParsedStream parsed = JBBPParser.prepare("structs[_] { ushort size; byte [size] payload; }").parse(theInStream).mapTo(ParsedStream.class);


来源:https://stackoverflow.com/questions/14776930/java-tcp-how-do-you-read-a-sent-stream-size-header-and-keep-reading-based-upon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!