Advenced Socket Programming - Sever到客户端的额外数据传输问题

Sub*_*der 1 java sockets nio

这里有一台服务器和一台客户端.并且通过可选择的频道维持了通信.喜欢 - 服务器---

  SelectionKey selectKey = channel.register(this.selector,

        SelectionKey.OP_ACCEPT);

while (selectKey.selector().select() > 0) {

    Set<SelectionKey> selectedKeys = this.selector.selectedKeys();

    Iterator<SelectionKey> iterator = selectedKeys.iterator();

    while (iterator.hasNext()) {

        SelectionKey key = iterator.next();

        iterator.remove();

        if (key.isAcceptable()) {

            ServerSocketChannel nextChannel = (ServerSocketChannel) key

                        .channel();
            SocketChannel newChannel = nextChannel.accept();

            newChannel.configureBlocking(false);

            if (!newChannel.isRegistered()) {

                SelectionKey selectionKey = newChannel.register(

                     this.selector, SelectionKey.OP_READ

                | SelectionKey.OP_WRITE);

                selectionKey.attach(newChannel);

            }

        } else if (key.isWritable()) {

             SocketChannel attachment1 = (SocketChannel)key.attachment();
             ByteBuffer writeBuffer = ByteBuffer.wrap("Hello".getBytes());

                attachment1.write(writeBuffer);

                System.out.print("Written");
            }
         }
      } 
Run Code Online (Sandbox Code Playgroud)

客户:

   InetSocketAddress isa = new InetSocketAddress(InetAddress
            .getLocalHost(), 4444);
    SocketChannel sc = null;

    try {

        while (true) {

            Thread.sleep(10000);
            sc = SocketChannel.open();
            sc.connect(isa);
            ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
            int nbytes = sc.read(byteBuffer);
            byteBuffer.flip();
            dbuf.flip();
            CharBuffer cb = decoder.decode(byteBuffer);
            System.out.println(isa + " : " + cb);

        }
Run Code Online (Sandbox Code Playgroud)

问题是每次客户端读取数据达到客户端缓冲区限制的全部大小而不是发送数据限制.

Dar*_*ron 5

这是TCP套接字工作的方式 - 它们是字节流,而不是消息序列.

您需要在更高级别的协议中进行设计,以便接收方在收到字节后可以重新发现消息边界.