您好,登錄后才能下訂單哦!
本篇內容主要講解“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。