1,不断重复广播一则新闻。
- packageMulSocket.fromBook;
- importjava.net.*;
- publicclassBroadCastextendsThread{
- Strings="今天天气好晴朗,处处好风光!";
- intport=5858;//组播的端口
- InetAddressgroup=null;//组播组
- MulticastSocketsocket=null;//多点广播套接字
- BroadCast(){
- try{
- group=InetAddress.getByName("239.255.8.0");//设置组播组为239.255.8.0
- socket=newMulticastSocket(port);//多点广播套接字将在port端口广播
- socket.setTimeToLive(0);//多点广播套接字发送数据报范围为本地网络
- socket.joinGroup(group);
- //加入组播组,加入group后,socket发送的数据报可以被加入到group中的成员接收到
- }catch(Exceptione){
- }
- }
- publicvoidrun(){
- while(true){
- try{
- DatagramPacketpacket=null;//待广播的数据报
- bytedata[]=s.getBytes();
- packet=newDatagramPacket(data,data.length,group,port);
- System.out.println(newString(data));
- socket.send(packet);//广播数据报
- sleep(2000);
- }catch(Exceptione){
- System.out.println(e.toString());
- break;
- }
- }
- }
- publicstaticvoidmain(Stringargs[]){
- newBroadCast().start();
- }
- }
2加入组播组,接收广播数据
- packageMulSocket.fromBook;
- importjava.net.*;
- importjava.awt.*;
- importjava.awt.event.*;
- importjavax.swing.*;
- publicclassReceiveextendsJFrameimplementsRunnable,ActionListener{
- privatestaticfinallongserialVersionUID=1L;
- intport;//组播的端口
- InetAddressgroup=null;//组播组的地址
- MulticastSocketsocket=null;//多点广播套接字
- JButtonstartReceive,stopReceive;
- JTextAreashowArea;
- Threadthread;//负责接收信息的线程
- booleanstop=false;
- publicReceive(){
- super("定时接收信息");
- thread=newThread(this);
- startReceive=newJButton("开始接收");
- stopReceive=newJButton("停止接收");
- startReceive.addActionListener(this);
- stopReceive.addActionListener(this);
- showArea=newJTextArea(10,10);
- JPanelnorth=newJPanel();
- north.add(startReceive);
- north.add(stopReceive);
- Containercon=getContentPane();
- con.add(north,BorderLayout.NORTH);
- con.add(newJScrollPane(showArea),BorderLayout.CENTER);
- port=5858;
- try{
- //初始化一气呵成
- group=InetAddress.getByName("239.255.8.0");
- socket=newMulticastSocket(port);
- socket.joinGroup(group);
- }catch(Exceptione){
- }
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setSize(320,300);
- validate();
- setVisible(true);
- }
- publicvoidactionPerformed(ActionEvente){
- if(e.getSource()==startReceive){
- if(!(thread.isAlive())){
- thread=newThread(this);
- stop=false;
- }
- try{
- thread.start();
- }catch(Exceptionee){
- }
- }
- if(e.getSource()==stopReceive){
- stop=true;
- }
- }
- publicvoidrun(){
- while(true){
- bytedata[]=newbyte[8192];
- DatagramPacketpacket=null;
- packet=newDatagramPacket(data,data.length,group,port);
- try{
- socket.receive(packet);
- Stringmessage=newString(packet.getData(),0,packet
- .getLength());
- showArea.append("/n"+message);
- showArea.setCaretPosition(showArea.getText().length());
- }catch(Exceptione){
- }
- if(stop==true)
- break;
- }
- }
- publicstaticvoidmain(Stringargs[]){
- newReceive();
- }
- }
思路明确简单易懂。