我有一臺服務器使用非阻塞套接字nio。服務器在單獨的線程中工作,並且有另一個稱爲遊戲的線程。遊戲線程保存服務器對象並使用server.sendMessage,服務器線程只讀取數據。當我在一個while循環中連續兩次調用sendMessage兩次數據包後,我在客戶端得到「java.io.StreamCorruptedException:invalid stream header:6B6574B4」錯誤。服務器代碼Sequentally Channel Write在Java.NIO中發送損壞的數據
部分:
public void write(SelectionKey channelKey, byte[] buffer) {
if (buffer != null) {
int bytesWritten;
try {
SocketChannel channel = (SocketChannel) channelKey.channel();
synchronized (channel) {
bytesWritten = channel.write(ByteBuffer.wrap(buffer));
}
if (bytesWritten == -1) {
resetKey(channelKey);
disconnected(channelKey);
}
} catch (Exception e) {
resetKey(channelKey);
disconnected(channelKey);
}
}
}
public void broadcast(byte[] buf, SelectionKey fr) {
synchronized (clientList) {
Iterator<SelectionKey> i = clientList.iterator();
while (i.hasNext()) {
SelectionKey key = i.next();
if (fr != key)
write(key, buf);
}
}
}
public synchronized void sendMessage(Packets pk) {
broadcast(pk.toByteArray(), null);
}
+1對於「循環」,但你應該提到循環不是字面上的while(!allWritten){write(lastPartOfBuf();}',它是異步操作鏈。 – 2013-05-09 01:00:50