我正在制作一个非常简单的多播应用程序,其中控制器通过简单的消息锁定和解锁电台。控制器和工作站都有接收线程。出于某种原因,发送第一条消息时,接收良好,但发送第二条消息时,接收不正确,其中附加了一些第一条消息。
例如,
Station 1 sends a "Locked: 1001" message.
The controller receives this message correctly.
The controller sends a "Unlock: 1001" message.
Station 1 receives something like "Unlock: 1ocked: 1001"
这是电台的接收器:
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;
}
}
}
这是发送控制器消息的地方:
private String unlockMsg = "Unlock: ";
public void unlockStation(int lockedID) {
//send packet telling station to unlock
String completeMsg = unlockMsg+lockedID;
byte buf[] = completeMsg.getBytes();
// Create and send the 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();
}
}
}
我知道这可能是初学者的问题,但我一般对多播和网络没有太多经验。