Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

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

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
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...