我的目標是發送不同類型的消息從客戶端到服務器,它將基於文本。我不確定的是如何在這裏刪除部分讀取。我必須確保我得到一個完整的信息,而不是更多。爪哇尼奧部分閱讀
有沒有人有這方面的經驗?
這是我到目前爲止有:
private void handleNewClientMessage(SelectionKey key) throws IOException {
SocketChannel sendingChannel = (SocketChannel) key.channel();
ByteBuffer receivingBuffer = ByteBuffer.allocate(2048);
int bytesRead = sendingChannel.read(receivingBuffer);
if (bytesRead > 0) {
receivingBuffer.flip();
byte[] array = new byte[receivingBuffer.limit()];
receivingBuffer.get(array);
String message = new String(array);
System.out.println("Server received " +message);
}
selector.wakeup();
}
但我沒有「結束」的消息的方式肯定有一個完整的消息。
最好的問候, Ø
您應該在套接字上添加文本協議。像HTTP一樣。 – Nikolai 2013-04-25 14:40:19
Hi @Nikolai。這聽起來不錯,你有鏈接到這裏的例子嗎?乾杯! – olemara 2013-04-30 08:02:46
HTTP就是一個實際的例子。您可以使用HttpComponents庫來解析HTTP協議。 – Nikolai 2013-04-30 12:28:18