3

我尝试使用端口 5500 将多播主机设置为 230.0.0.1。然后,在另一边,我说在端口 5500 加入组 230.0.0.1。它加入并接收数据包几秒钟。然后它突然停止了。如果我使用 255.255.255.255 它会正常接收数据包。为什么会这样?多播发送方的代码如下:

private class StatusBroadcasterThread extends Thread
{

    private static final boolean DEBUG = App.DEBUG;
    private static final String TAG = "StatusBroadcasterThread";

    private DatagramSocket broadcastSocket;

    public StatusBroadcasterThread(int port) throws SocketException {

        broadcastSocket = new DatagramSocket(port);

        this.start();
    }

    @Override
    public void run() {

        while (!this.isInterrupted()) {

            try {

                byte[] buffer = status.toString().getBytes(); 

                DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(App.Config.multicastAddress),
                        App.Config.multicastPort);

                broadcastSocket.send(packet);

                if (DEBUG)                      
                    Log.d(TAG, "Sent: " + new String(packet.getData()));

            } catch (IOException e) {

                Log.e(TAG, "Error: " + e.getMessage());
            }

            try {
                sleep(App.Config.broadcastInterval);
            } catch (InterruptedException ex) {
            }
        }
    }
}

接收线程:

private class ReceiverThread extends Thread
{

    private static final String TAG = ComMessageReceiver.TAG + "Thread";

    private WifiManager wifiManager;
    private MulticastSocket multicastSocket;
    private InetSocketAddress groupInetSocketAddress;
    private boolean joinedGroup = false;

    public ReceiverThread(String group, int port, int timeout) throws IOException {

        super();

        wifiManager = (WifiManager) App.context.getSystemService(Context.WIFI_SERVICE);
        groupInetSocketAddress = new InetSocketAddress(InetAddress.getByName(group), port);
        multicastSocket = new MulticastSocket(port);
        multicastSocket.setSoTimeout(timeout);

    }

    public ReceiverThread() throws IOException {

        this(Config.multicastAddress, Config.multicastPort, DEFAULT_TIMEOUT);
    }

    @Override
    public void run() {

        Log.d(TAG, "started");

        while (!this.isInterrupted()) {

            if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

                if (!joinedGroup) {

                    try {

                        multicastSocket.joinGroup(groupInetSocketAddress,
                                NetworkInterface.getByInetAddress(getWifiInetAddress()));

                        wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
                        wifiManager.createMulticastLock(TAG).acquire();

                        joinedGroup = true;

                    } catch (IOException ex) {

                        Log.e(TAG, "Failed to join Multicast group: " + ex.getMessage());
                    }
                }

                try {

                    byte[] buffer = new byte[256];

                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    multicastSocket.receive(packet);

                    Message message = new Message(packet);

                    Log.d(TAG, "message from " + message.getIp() + " " + message.getMsg());

                    for (MessageListener listener : listenerList)
                        listener.onMessageReceived(message);

                } catch (SocketTimeoutException ex) {

                    Log.e(TAG, "Timed out: " + ex.getMessage());

                } catch (IOException ex) {

                    Log.e(TAG, ex.getMessage());
                }
            } else
                joinedGroup = false;
        }
    }

    InetAddress getWifiInetAddress() throws UnknownHostException {

        ByteBuffer wifiRawAddress = ByteBuffer.allocate(4);
        wifiRawAddress.order(ByteOrder.LITTLE_ENDIAN).putInt(wifiManager.getConnectionInfo().getIpAddress());

        return InetAddress.getByAddress(wifiRawAddress.array());
    }

}
4

1 回答 1

3

1. 255.255.255.255不是地址,而是广播地址。

2.请检查您是否在通信完成时正确关闭了套接字。

请参阅下面的所有组播地址列表............

224.0.0.0   Base address (reserved)
224.0.0.1   The All Hosts multicast group addresses all hosts on the same network segment.
224.0.0.2   The All Routers multicast group addresses all routers on the same network segment.
224.0.0.4   This address is used in the Distance Vector Multicast Routing Protocol (DVMRP) to address multicast routers.
224.0.0.5   The Open Shortest Path First (OSPF) All OSPF Routers address is used to send Hello packets to all OSPF routers on a network segment.
224.0.0.6   The OSPF All D Routers address is used to send OSPF routing information to designated routers on a network segment.
224.0.0.9   The Routing Information Protocol (RIP) version 2 group address is used to send routing information to all RIP2-aware routers on a network segment.
224.0.0.10  The Enhanced Interior Gateway Routing Protocol (EIGRP) group address is used to send routing information to all EIGRP routers on a network segment.
224.0.0.13  Protocol Independent Multicast (PIM) Version 2
224.0.0.18  Virtual Router Redundancy Protocol (VRRP)
224.0.0.19 - 21     IS-IS over IP
224.0.0.22  Internet Group Management Protocol (IGMP) Version 3
224.0.0.102     Hot Standby Router Protocol version 2 (HSRPv2) / Gateway Load Balancing Protocol (GLBP)
224.0.0.107     Precision Time Protocol version 2 peer delay measurement messaging
224.0.0.251     Multicast DNS (mDNS) address
224.0.0.252     Link-local Multicast Name Resolution (LLMNR) address
224.0.1.1   Network Time Protocol clients listen on this address for protocol messages when operating in multicast mode.
224.0.1.39  The Cisco multicast router AUTO-RP-ANNOUNCE address is used by RP mapping agents to listen for candidate announcements.
224.0.1.40  The Cisco multicast router AUTO-RP-DISCOVERY address is the destination address for messages from the RP mapping agent to discover candidates.
224.0.1.41  H.323 Gatekeeper discovery address
224.0.1.129 - 132   Precision Time Protocol version 1 time announcements
224.0.1.129     Precision Time Protocol version 2 time announcements
于 2012-07-24T16:24:03.787 回答