最近用到了MulticastSocket,发现在有些情况下它不能工作,当然这是编码的问题,是一个BUG,不过这个BUG较少出现,一旦出现了也让人摸不着头绪。
由于以前没有用过这个东东,首先在网上找了个简单的例子:
Server端:
1 import java.net.DatagramPacket;
2 import java.net.InetAddress;
3 import java.net.MulticastSocket;
4
5 public class Server {
6 public static void main(String [] arstring) {
7 try {
8 // Create a multicast datagram socket for receiving IP
9 // multicast packets. Join the multicast group at
10 // 230.0.0.1, port 7777.
11 MulticastSocket multicastSocket = new MulticastSocket(7777);
12 InetAddress inetAddress = InetAddress.getByName("230.0.0.1");
13 multicastSocket.joinGroup(inetAddress);
14 // Loop forever and receive messages from clients. Print
15 // the received messages.
16 while (true) {
17 byte [] arb = new byte [100];
18 DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length);
19 multicastSocket.receive(datagramPacket);
20 System.out.println(new String(arb));
21 }
22 }
23 catch (Exception exception) {
24 exception.printStackTrace();
25 }
26 }
27 }
Client端:
1 public class Client {
2 public static void main(String [] arstring) {
3 try {
4 // Create a datagram package and send it to the multicast
5 // group at 230.0.0.1, port 7777.
6 for (; ;) {
7 byte [] arb = new byte []{'h', 'e', 'l', 'l', 'o'};
8 InetAddress inetAddress = InetAddress.getByName("230.0.0.1");
9 DatagramPacket datagramPacket =
10 new DatagramPacket(arb, arb.length, inetAddress, 7777);
11 MulticastSocket multicastSocket = new MulticastSocket();
12 // multicastSocket.joinGroup(inetAddress);
13 multicastSocket.send(datagramPacket);
14 }
15 }
16 catch (Exception exception) {
17 exception.printStackTrace();
18 }
19 }
20 }
在公司编译、运行都正常,回到家里发现Server不能收到broadcast消息了。跟踪程序也没有发现问题,网上也没有找到答案。后来考虑到公司和家
里的网络情况不同:公司里是通过内网连接到INTERNET;在家则是在局域网上拨号连接到INTERNET,相当于有两个逻辑的网络接口卡。于是在上述
例子中增加如下代码:
multicastSocket.setNetworkInterface(NetworkInterface.getByInetAddress(InetAddress.getLocalHost()));
再次测试,成功!
总结:使用MulticastSocket时,如果发现broadcast不成功,要注意是否使用了多个网络接口卡(物理的或逻辑的)。