serialization - Sequentally Channel Write Sends Corrupted Data in Java.NIO -


i have server uses non blocking sockets, nio. server works in separate thread , there thread called game. game thread holds server object , uses server.sendmessage, server thread reads data. when call sendmessage 2 times sequentally 2 packets in while loop, after moment "java.io.streamcorruptedexception: invalid stream header: 6b6574b4" error in client.

part of server code :

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> = 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); } 

my guess (from small amount of code have included) not delineating messages @ all. though send 2 messages separately, io layer may split/combine in various ways such receiver gets part of 1 message attached previous message. should use sort of "message" protocol indicate receiver how many bytes consume can correctly parse each incoming message (e.g. write message byte length first, message bytes).

as side note, write() method not guaranteed write bytes in 1 call, should handling return value , writing remaining bytes necessary.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -