组播数据包很脏

时间:2014-04-14 11:17:16

标签: java multicast multicastsocket

我正在创建一个非常简单的多播应用程序,其中控制器通过简单的消息锁定和解锁一个站。控制器和站都有接收器线程。出于某种原因,当发送第一条消息时,它被很好地接收,但是当发送第二条消息时,它被错误地接收,并且附加了一些第一条消息。

例如,

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

我知道这可能是初学者的问题,但我对组播和网络方面的经验并不多。

2 个答案:

答案 0 :(得分:1)

问题是您没有注意收到的数据包的长度。变化

    msg = new String(pack.getData());

    msg = new String(pack.getData(), 0, pack.getLength());

第一次在代码中创建一个String时,它(种类)起作用....因为你然后trim()字符串去掉尾随的NUL(零)字符。

第二次,你正在读入一个脏缓冲区,所以垃圾是解码为非NUL字符。

FWIW,如果在创建String时使用数据包长度,则不再需要trim()来删除尾随的NUL字符。

答案 1 :(得分:0)

我怀疑您的问题是,您在现有缓冲区中收到了Datagram,该缓冲区中包含了之前Datagram收据中的数据。尝试为每次接收使用新的byte[]。我认为您还需要考虑进入的数据长度,然后查看this SO answer以使用pack.getLength()