简体   繁体   English

Java Socket OutputStream将一个byte []作为两个单独的消息写入

[英]Java Socket OutputStream write one byte[] as two separate messages

Trying to send a byte[] through TCP Socket in Java, it sends a specific array as two separate messages, while other arrays are sending as one message. 尝试通过Java中的TCP套接字发送byte []时,它将特定的数组作为两个单独的消息发送,而其他数组作为一个消息发送。 In more details, I convert a hex String to a byte[] using the following function: 更详细地讲,我使用以下函数将十六进制字符串转换为byte []:

public static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }

And then I send it through Java TCP Socket: 然后通过Java TCP套接字发送它:

ServerSocket server = new ServerSocket(3030);
Socket socket = server.accept();
OutputStream out = socket.getOutputStream();
// sample hex string
String msg = "F0700F8000F42400001544952414E00000000000000000000000662000E00060000";
out.write(HexUtiles.hexStringToByteArray(msg));

In debugging the code I found out it separate the array in byte number 1024. Also, increasing and decreasing the socket buffer size made no differences. 在调试代码时,我发现它将字节号为1024的数组分开。此外,增加和减小套接字缓冲区的大小也没有区别。

In addition, there is no 0A (Hex String of \\n ) in the message! 此外,消息中没有0A( \\n十六进制字符串)! I guess there is some strange behavior in the write method that sends a byte[] array as two messages! 我猜想在write方法中有一些奇怪的行为,它以两个消息的形式发送byte []数组! How can I send the byte[] as only one message? 我如何只将byte []作为一条消息发送?

There are no "messages" in TCP. TCP中没有“消息”。 Everything is sent as a stream and it's undefined how it will be chunked on the other end. 一切都作为流发送,并且在另一端如何分块尚不确定。 Chunks might be split or joined together. 块可能会拆分或合并在一起。

Send the byte size before each array using DataOutputStream . 使用DataOutputStream在每个数组之前发送字节大小。 Read the size on the other end using DataInputStream and then that many bytes. 使用DataInputStream读取另一端的大小,然后读取那么多字节。 This way you will be able to recreate your arrays at the other end. 这样,您将可以在另一端重新创建阵列。

Another option is to use ObjectOutputStream and ObjectInputStream and send the arrays as objects. 另一种选择是使用ObjectOutputStreamObjectInputStream并将数组作为对象发送。

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

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