我在ByteArray和Object流方面遇到问题。我正在通过NIO服务器创建一个多人纸牌游戏。我通过以下方法发送ArrayList private ArrayList<Card> cardsDropped
:
public void sendMessage(Object message) {
if (message instanceof String) {
messages.add(message + Config.MESSAGE_DELIMITER);
} else {
messages.add(message);
}
SelectionKey key = channel.keyFor(selector);
key.interestOps(OP_WRITE);
}
使用private final LinkedList<Object> messages
,这是流中通过发送的所有对象的列表
->客户端方法:
protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
ByteArrayInputStream byteObject = new ByteArrayInputStream(data);
ObjectInputStream obj;
in = null;
try {
obj = new ObjectInputStream(byteObject); //HERE <--
byteObject.close();
in = obj.readObject();
obj.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
handler.onMessage(in);
}
protected void write(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
while (!messages.isEmpty()) {
ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(byteObject);
oos.writeObject(messages.poll());
oos.flush(); //TODO ?
oos.close();
channel.write(ByteBuffer.wrap(byteObject.toByteArray()));
byteObject.close();
} catch (IOException e) {
e.printStackTrace();
}
}
key.interestOps(OP_READ);
}
和服务器方法:
protected void write(SelectionKey key) {
ByteBuffer buffer = (ByteBuffer) key.attachment();
SocketChannel channel = (SocketChannel) key.channel();
try {
channel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
for (SelectionKey key : selector.keys()) {
if (key.channel() instanceof ServerSocketChannel) {
continue;
}
if (key.equals(sender)) {
continue;
}
key.attach(ByteBuffer.wrap(data));
write(key);
}
}
一些回合和卡片发送后,客户端线程在这里obj = new ObjectInputStream(byteObject);
向我发送了一些“无效的流头”
这是与服务器/客户端代码的编写方式有关的问题吗? [代码基于https://github.com/mpkelly/nio-chat]
谢谢!