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가있는 일반적인 함정에 대한 것입니다. 적용 가능합니다. –