美文网首页
14.Scatter And Gather

14.Scatter And Gather

作者: 未知的证明 | 来源:发表于2019-03-04 21:01 被阅读0次
package com.liyuanfeng.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class NioTest11 {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(8899);
        serverSocketChannel.socket().bind(address);

        int messageLength = 2 + 3 + 4;
        ByteBuffer[] byteBuffers = new ByteBuffer[3];
        byteBuffers[0] = ByteBuffer.allocate(2);
        byteBuffers[1] = ByteBuffer.allocate(3);
        byteBuffers[2] = ByteBuffer.allocate(4);

        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {

                long read = socketChannel.read(byteBuffers);
                byteRead += read;

                System.out.println("byteRead:" + byteRead);

                Arrays.stream(byteBuffers).map(buffer -> "position:" + buffer.position() + ",limit" + buffer.limit()).forEach(System.out::println);

            }

            Arrays.stream(byteBuffers).forEach(Buffer::flip);
            long bytesWritten = 0;
            while (bytesWritten < messageLength) {
                long r = socketChannel.write(byteBuffers);
                bytesWritten += r;
            }

            Arrays.stream(byteBuffers).forEach(Buffer::clear);

            System.out.println("bytesRead:" + byteRead + ",bytesWritten:" + bytesWritten + ",messageLength:" + messageLength);
        }
    }
}

相关文章

网友评论

      本文标题:14.Scatter And Gather

      本文链接:https://www.haomeiwen.com/subject/feywuqtx.html