潜鱼在渊

Concentrating on Architectures.

posts - 77, comments - 309, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

为什么MulticastSocket不能正常工作?

Posted on 2006-06-28 23:35 非鱼 阅读(4106) 评论(2)  编辑  收藏 所属分类: Java技术
    最近用到了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不成功,要注意是否使用了多个网络接口卡(物理的或逻辑的)。

评论

# re: 为什么MulticastSocket不能正常工作?  回复  更多评论   

2006-06-29 19:59 by lizongbo

我昨天调试rmi也遇到类似的问题。

也是双网卡,死活会先认内网ip,后来终于找到原因了,呵呵

# re: 为什么MulticastSocket不能正常工作?  回复  更多评论   

2007-10-24 11:57 by 青铜人
我也遇到这个情况,但这解决不了。请楼主加我qq:278216928帮我呀

只有注册用户登录后才能发表评论。


网站导航: