-1

我正在使用以下代码读取大文件,并通过缓冲区通过 TCP 连接缓冲区发送文件内容。在每次发送结束时,TCP 通道添加一个 CRLF 字符。除非我添加它,否则我不希望它出现在结果中。

        final int BUFFER_SIZE = 65536;
    long bytesToSkip = 0;
    byte[] buffer = new byte[BUFFER_SIZE];

    try (RandomAccessFile rand = new RandomAccessFile(new File(requestModel.getFilePath()), "r");
    ) {

        rand.seek(bytesToSkip);
        while ((read = rand.read(buffer)) != -1) {

            MessageBuilder mb = MessageBuilder.withPayload(buffer).setHeaderIfAbsent(IpHeaders.CONNECTION_ID, connectionId);
            outMsgChannel.send(mb.build())

            buffer = new byte[BUFFER_SIZE];
        }
    }
    catch(Exceptions .............. 

添加新行的示例输出。(两个缓冲区都很大。我只提到了在每个缓冲区末尾引起问题的行)

包含缓冲区一

一只敏捷的棕色狐狸跳过懒惰的狗

一只敏捷的棕色狐狸跳过懒惰的狗

一只敏捷的棕色狐狸跳过

缓冲区二包含

懒狗

如果没有不需要的 CRLF,那么我将不会在输出中遇到单行拆分为两行的问题。我只想在文件所在的位置添加新行。

4

1 回答 1

2

See the documentation.

TCP is a streaming protocol; this means that some structure has to be provided to data transported over TCP, so the receiver can demarcate the data into discrete messages. Connection factories are configured to use (de)serializers to convert between the message payload and the bits that are sent over TCP. This is accomplished by providing a deserializer and serializer for inbound and outbound messages respectively. A number of standard (de)serializers are provided.

The ByteArrayCrlfSerializer, converts a byte array to a stream of bytes followed by carriage return and linefeed characters (\r\n). This is the default (de)serializer and can be used with telnet as a client, for example.

...

You need some way to know when the message is complete - the underlying network might packetize your message so it is received in chunks.

The ByteArrayRawSerializer adds no characters to the message; it might satisfy your needs. When used on the reading side, it uses the socket EOF to indicate the message is complete.

于 2017-07-05T13:39:34.703 回答