本篇内容主要讲解“java怎么实现组播”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java怎么实现组播”吧!
MulticastSocket multicastSocket;@FXMLButton btnmuticast,btnmuticaststop;public void btnmuticastOnMouseClicked(MouseEvent event) {try {multicastSocket = new MulticastSocket(3001); multicastSocket.setInterface(InetAddress.getByName("192.168.1.101")); InetAddress multiaddr = InetAddress.getByName("224.26.83.1"); multicastSocket.joinGroup(multiaddr); multicastSocket.setTimeToLive(4); byte[] buff = "QQ".getBytes(); DatagramPacket datagramPacket = new DatagramPacket(buff,buff.length,multiaddr,3001); multicastSocket.send(datagramPacket); logger.info("btnmuticastOnMouseClicked"); } catch (IOException e) { e.printStackTrace(); } }public void bbtnmuticaststopOnMouseClicked(MouseEvent event) {if((multicastSocket!= null) && (multicastSocket.isConnected())) {logger.info("bbtnmuticaststopOnMouseClicked"); multicastSocket.close(); } }
接收端:
public class MulticastReceive { public static void main(String[] args) throws Exception { listener(); } public static void listener() throws Exception{ //组播地址 InetAddress group = InetAddress.getByName("224.0.0.1"); int port = 8888; //创建组播套接字 MulticastSocket msr = null; try { msr = new MulticastSocket(port); //加入连接 msr.joinGroup(group); byte[] buffer = new byte[8192]; System.out.println("接收数据包启动!(启动时间: "+new Date()+")"); while(true){ //建立一个指定缓冲区大小的数据包 DatagramPacket dp = new DatagramPacket(buffer, buffer.length); msr.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); //解码组播数据包 System.out.println(s); } } catch (Exception e) { e.printStackTrace(); }finally{ if(msr!=null){ try { msr.leaveGroup(group); msr.close(); } catch (Exception e2) { } } } } }
发送端:
public class MulticastSender { public static void server() throws Exception{ InetAddress group = InetAddress.getByName("224.0.0.1");//组播地址 int port = 8888; MulticastSocket mss = null; try { mss = new MulticastSocket(port); mss.joinGroup(group); System.out.println("发送数据包启动!(启动时间"+new Date()+")"); while(true){ String message = "Hello "+new Date(); byte[] buffer = message.getBytes(); DatagramPacket dp = new DatagramPacket(buffer, buffer.length,group,port); mss.send(dp); System.out.println("发送数据包给 "+group+":"+port); TimeUnit.SECONDS.sleep(1); } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(mss!=null){ mss.leaveGroup(group); mss.close(); } } catch (Exception e2) { } } } public static void main(String[] args) throws Exception { server(); } }
到此,相信大家对“java怎么实现组播”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。