本篇內(nèi)容主要講解“java怎么實現(xiàn)組播”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“java怎么實現(xiàn)組播”吧!
成都創(chuàng)新互聯(lián)公司是一家專業(yè)從事網(wǎng)站設(shè)計制作、做網(wǎng)站的網(wǎng)絡(luò)公司。作為專業(yè)網(wǎng)站制作公司,成都創(chuàng)新互聯(lián)公司依托的技術(shù)實力、以及多年的網(wǎng)站運營經(jīng)驗,為您提供專業(yè)的成都網(wǎng)站建設(shè)、營銷型網(wǎng)站及網(wǎng)站設(shè)計開發(fā)服務(wù)!
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; //創(chuàng)建組播套接字 MulticastSocket msr = null; try { msr = new MulticastSocket(port); //加入連接 msr.joinGroup(group); byte[] buffer = new byte[8192]; System.out.println("接收數(shù)據(jù)包啟動!(啟動時間: "+new Date()+")"); while(true){ //建立一個指定緩沖區(qū)大小的數(shù)據(jù)包 DatagramPacket dp = new DatagramPacket(buffer, buffer.length); msr.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); //解碼組播數(shù)據(jù)包 System.out.println(s); } } catch (Exception e) { e.printStackTrace(); }finally{ if(msr!=null){ try { msr.leaveGroup(group); msr.close(); } catch (Exception e2) { } } } } }
發(fā)送端:
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("發(fā)送數(shù)據(jù)包啟動?。▎訒r間"+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("發(fā)送數(shù)據(jù)包給 "+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怎么實現(xiàn)組播”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!