简体   繁体   English

Java TCP Socket接收具有指定长度的字节

[英]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. 我试图先读取4个byte(int),以指定消息的大小,然后再根据字节数读取其余字节。 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: readUTF的JavaDocs

First, two bytes are read and used to construct an unsigned 16-bit * integer * in exactly the manner of the readUnsignedShort method . 首先, 读取两个字节,并以与readUnsignedShort方法完全相同的方式构造一个无符号的16位 * 整数 *。 This integer value is called the UTF length and specifies the number of additional bytes to be read . 此整数值称为UTF长度,它指定要读取的其他字节数 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. 唯一的问题是您的协议似乎仅发送4个字节作为有效载荷长度。 Perhaps you can do a similar method but increase the size of length sentinel read to 4 bytes/32-bits. 也许您可以执行类似的方法,但是将前哨读取的长度增加到4字节/ 32位。

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." 另外,我看到您只是在做新的String(bytes),只要数据编码与“平台的默认字符集”相同,它就可以正常工作。 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). 请参见javadoc。因此,仅确保您正确地对其进行编码会更安全(例如,如果您知道发送方以UTF-8格式发送它,则改为使用新的String(bytes,“ UTF-8”))。

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 您可以像这样使用read(byte[] b, int off, int len)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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