问题
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