SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int numRead = -1;
try {
numRead = channel.read(buffer);
System.out.println("numRead: " + numRead);
}
catch (IOException e) { e.printStackTrace();}
if (numRead == -1) {
this.dataMap.remove(channel);
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
System.out.println("Connection closed by client: " + remoteAddr);
channel.close();
key.cancel();
return;
}
System.out.println("Got: " + new String(buffer.array(), "windows-1251"));
從套接字讀取1024個字節的數據。在這種情況下,所有消息都被組合在一起,並且最後一條消息不會完全消失。如何在消息分隔符'|'之前將數據讀入緩衝區?我想單獨收到每封郵件。Java SocketChannel讀取未知長度的消息
套接字API爲您做到這一點。就像它已經在緩衝區中一樣。 – Woot4Moo
這裏是一個很好的閱讀。 https://github.com/robbiehanson/CocoaAsyncSocket/wiki/CommonPitfalls談論你在問什麼。該庫是爲obj - c的,但文章是關於tcp/udp常見的陷阱,所以它適用 –