I have problems with ByteArray and Object streams. I'm creating a multiplayer card game via NIO server. I send the ArrayList private ArrayList<Card> cardsDropped
through the method:
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);
}
With private final LinkedList<Object> messages
that is the list of all objects sent in the stream through
-> Client methods:
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);
}
And Server methods:
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);
}
}
After some turns and cards sent, Client thread is sending me some "invalid stream header" here obj = new ObjectInputStream(byteObject);
Is this a problem related to how is the server/client code written? [The code is based on https://github.com/mpkelly/nio-chat ]
Thanks in advance!