十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本篇内容主要讲解“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怎么实现组播”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!