Java NIO Socket Channel mismatch in size of sent and received bytes

ぃ、小莉子 提交于 2019-12-13 08:01:06

问题


I have the server and the client. Server sends data using this:

private int writeMessage(AgentHandler agentHandler, Msg message) {
    SocketChannel sc = agentHandler.getSocketChannel();
    byte[] encodedMessage = Encoder.INSTANCE.encode(message);
    ByteBuffer writeBuffer = ByteBuffer.wrap(encodedMessage);
    int count = 0;
    while (writeBuffer.hasRemaining()) {
        try {
            int written = sc.write(writeBuffer);
            count += written;
        } catch (IOException e) {
            deregisterAgent(agentHandler.getAgentID());
        }
    }
    System.out.printf("Written bytes: %s\n", count);
    return count;
}

and I have the output:

Written bytes: 31904

Client receives data using next piece of code:

private void readFromSockets() {
    int readReady = 0;
    try {
        readReady = readSelector.select();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (readReady > 0) {
        Set<SelectionKey> selectedKeys = readSelector.selectedKeys();
        Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            if (key.isReadable())
                readFromSocket(key);
            keyIterator.remove();
        }
        selectedKeys.clear();
    }
}



private void readFromSocket(SelectionKey key)  {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);
    SocketChannel socketChannel = (SocketChannel) key.channel();
    int counter = 0, bytesRead;
    try {
        while ((bytesRead = socketChannel.read(byteBuffer)) != 0) {
            if (bytesRead == -1) {
                System.out.println("Socket channel seems disconnected.");
                try {
                    socketChannel.close();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
            counter += bytesRead;
            System.out.println("reading from socket...");
        }

    } catch (IOException e) {
        System.out.println("Socket Channel IO exception catched");
        try {
            socketChannel.close();
            return;
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }
    }
    System.out.println("Bytes received " + counter);

    byteBuffer.flip();
    byte[] message = new byte[counter];
    byteBuffer.get(message, 0, counter);
    Msg incomingMessage = Encoder.INSTANCE.decode(message);
    if (incomingMessage != null) {
        processMessage(incomingMessage);
    }
}

and client output

Bytes received 14828

This issue can be represented only in case of really remote connection (server and client in another countries in my case).

When I test my code on localhost, I have no problem.

I need an advice how I can fix this.


回答1:


Sounds like you’re experiencing a temporary gap in the data stream. If you simply continue reading, you’ll eventually get all of the message bytes. Unfortunately, with your current setup, you can’t tell when you’ve reached the end of the message, whether there is more bytes to come, or if you’ve got part of the next message!

Write the number of bytes in the message out through the socket, followed by the message itself. When reading, read the message length, then read the message bytes until the complete message is read.



来源:https://stackoverflow.com/questions/49283971/java-nio-socket-channel-mismatch-in-size-of-sent-and-received-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!