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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…