java - Multicast packets come in dirty -
i'm making simple multicast application controller locks , unlocks station via simple messages. controller , station both have receiver threads. reason, when first message sent, received well, when second message sent, received incorrectly, of first message attached it.
for example,
station 1 sends "locked: 1001" message. controller receives message correctly. controller sends "unlock: 1001" message. station 1 receives "unlock: 1ocked: 1001"
here's station's receiver:
public class votingstationreceiver implements runnable{ private dummyvotingstation votingstation; private multicastsocket s; private thread listener = new thread(this); public votingstationreceiver(multicastsocket s, dummyvotingstation votingstation){ this.s = s; this.votingstation = votingstation; listener.start(); } public void run() { byte[] buf = new byte[1024]; while(true) try { datagrampacket pack = new datagrampacket(buf, buf.length); s.receive(pack); string msg = ""; msg = new string(pack.getdata()); msg = msg.trim(); system.out.println(msg); system.out.println("voting station: message received"); votingstation.processmessage(msg); } catch(ioexception e) { break; } } }
and here's controller's message sent:
private string unlockmsg = "unlock: "; public void unlockstation(int lockedid) { //send packet telling station unlock string completemsg = unlockmsg+lockedid; byte buf[] = completemsg.getbytes(); // create , send datagrampacket datagrampacket pack; try { pack = new datagrampacket(buf, buf.length, inetaddress.getbyname(group), port); int ttl = s.gettimetolive(); s.settimetolive(ttl); s.send(pack); system.out.println("control station: message sent"); } catch (unknownhostexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } }
i know beginner's problem, don't have experience multicasting , networking in general.
i suspect problem you're receiving datagram
existing buffer that's had data in previous datagram
receipt. try using new byte[]
each receive. think need consider length of data coming in , consequently check out this answer make use of pack.getlength()
Comments
Post a Comment