TCP:读/写POJO

时间:2015-05-04 00:36:35

标签: java tcp io pojo

我必须通过仅连接一次的TCP传输POJO。我使用以下代码发送和接收数据。

public static void sendPacket(DataPacket packet, OutputStream out) throws Exception {
    if (packet != null) {
        byte[] lenArray = new byte[2];
        byte[] data = ReadAndWriteFileUtil.serializeObject(packet);
        lenArray[0] = (byte) (data.length >>> 8);
        lenArray[1] = (byte) (data.length & 0xFF);

        byte[] serializedPacket = new byte[2 + data.length];

        System.arraycopy(lenArray, 0, serializedPacket, 0, 2);
        System.arraycopy(data, 0, serializedPacket, 2, data.length);

        System.out.println("Send Length: " + (serializedPacket.length-2));
        out.write(serializedPacket);
        //out.flush();
    }
}

public static byte[] receivePacket(InputStream in) throws Exception {
    byte[] buf = receivePacket(2, in);
    int length = ((buf[0] & 0xFF) << 8) + (buf[1] & 0xFF);

    System.out.println("Length: " + length);

    byte[] data = receivePacket(length, in);
    return data;
}

private static byte[] receivePacket(int length, InputStream in)
        throws Exception {
    int dataRec = 0;
    byte[] data = new byte[length];

    while (dataRec < length) { 
        long n = in.read(data);
        if (n < 0) {
            break;
        }
        dataRec += (int) n;
    }
    if(dataRec <= 0) {
        data = null;
    }
    return data;
}

问题: 发送DataPacket时大小= 516字节。但是在接收数据包时,我无法只接收516个字节。

例如:我收到的数据长度为

长度:516
长度:516
长度:516
长度:516
长度:3840
长度:3840
长度:516
长度:516
长度:516
长度:9728
长度:37888
长度:42948

但每个数据包的长度应为516。

我做错了什么。请建议。

提前致谢。

0 个答案:

没有答案