简体   繁体   中英

Java TCP Socket receiving bytes with specified length

I am trying to first read 4 bytes(int) specifying the size of the message and then read the remaining bytes based on the byte count. I am using the following code to accomplish this:

DataInputStream dis = new DataInputStream(
                        mClientSocket.getInputStream());

// read the message length
int len = dis.readInt();

Log.i(TAG, "Reading bytes of length:" + len);

// read the message data
byte[] data = new byte[len];
if (len > 0) {
    dis.readFully(data);
} else {
    return "";
}
return new String(data);

Is there a better/efficient way of doing this?

From JavaDocs of readUTF:

First, two bytes are read and used to construct an unsigned 16-bit * integer * in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read . These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

The only problem with this is that your protocol seems to only send 4 bytes for the payload length. Perhaps you can do a similar method but increase the size of length sentinel read to 4 bytes/32-bits.

Also, I see that you are just doing new String(bytes) which works fine as long as the encoding of the data is the same as "the platform's default charset." See javadoc So it would be much safer to just ensure that you are encoding it correctly(eg if you know that the sender sends it as UTF-8 then do new String(bytes,"UTF-8") instead).

How about

DataInputStream dis = new DataInputStream(new BufferedInputStream(
                     mClientSocket.getInputStream()));

return dis.readUTF();

You can use read(byte[] b, int off, int len) like this

byte[] data = new byte[len];
dis.read(data,0,len);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM