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 字节的数据。在这种情况下,所有消息都被合并,最后一条消息没有完全到达。如何在消息分隔符“|”之前将数据读入缓冲区 ? 我想单独接收每条消息。