0

我正在制作一个接收消息的java NIO服务器,每条消息在消息的头部都有它的大小,这就是为什么我首先读入一个默认大小(44)的缓冲区,然后从这个缓冲区中获取完整的大小,然后创建一个新缓冲区,该缓冲区应该获取消息(正文)的其余部分,然后使用 System.arrayCopy() 制作包含完整消息的数组。此操作运行良好,问题是第二个缓冲区(消息体)具有大小但不包含正确的数据。如果你有什么问题,请这是我的代码:

public void getMessageByMessageSize(SelectionKey key) {
    socket = (SocketChannel) key.channel();
    int nBytes = 0;
    byte[] message = null;
    try {
        nBytes = socket.read(headBuffer);
        if (nBytes < 0) {
            try {
                key.channel().close();
                key.cancel();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
                    //size of the message body
        int corpMessageSize = MessageUtils.getMessageSize(headBuffer)
                - HEADER_SIZE;
        ByteBuffer corpsBuffer = ByteBuffer.allocate(corpMessageSize);
        headBuffer.flip();
        nBytes += socket.read(corpsBuffer);
        corpsBuffer.flip();
        byte[] corp=corpsBuffer.array();

        message = new byte[nBytes];
        System.arraycopy(headBuffer.array(), 0, message, 0, HEADER_SIZE);
        System.arraycopy(corpsBuffer.array(), 0, message, HEADER_SIZE,
                nBytes - HEADER_SIZE);
        System.out.println(nBytes);
        headBuffer.clear();
        corpsBuffer.clear();
    } catch (IOException e) {
        e.printStackTrace();
        try {
            key.channel().close();
            key.cancel();
            return;
        } catch (IOException ex) {
            e.printStackTrace();
        }
    }

    this.worker.verifyConnection(this,message, key);
    //this.worker.processData(this, socket, message, nBytes);
}

我有一个简单的客户端,它发送创建一个字节消息,在头部确定它的大小,然后发送它。

谢谢

4

1 回答 1

1

nBytes += socket.read(corpsBuffer);

您假设这会读取整个消息并填充缓冲区。TCP/IP 中没有任何东西可以保证这一点。你必须循环。如果您处于非阻塞模式,则必须重新选择是否获得零长度读取。

于 2012-07-12T23:18:01.123 回答