Java基于UDP的多点广播数据报技术的一个实现例子


This is a UDP network program. The following presents a multicast datagram program, which is actually a new technology.

[java]

  1. package com.han;  
  2. import java.net.*;  
  3. /** 
  4.  * This is a UDP network program. 
  5.  * The following presents a multicast datagram program, 
  6.  * which is actually a new technology. 
  7.  *  
  8.  * @author HAN 
  9.  * 
  10.  */  
  11. public class Weather extends Thread{  
  12.     String weather ="节目预告: 八点有大型晚会,请收听";  
  13.     int port =9898;  
  14.     InetAddress iaddress;//没法初始化,这里只能声明。因为初始化new对象时要抛出异常所以在成员变量区域是语法通不过的。   
  15.     MulticastSocket socket;  
  16.     //在构造方法中初始化成员变量   
  17.     Weather(){  
  18.         try {  
  19.             //A multicast group is specified by a class D IP address    
  20.             //and by a standard UDP port number.   
  21.             //Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive.   
  22.             //The address 224.0.0.0 is reserved and should not be used.   
  23.             iaddress=InetAddress.getByName("233.0.0.0");  
  24.             socket=new MulticastSocket(port);  
  25.             socket.setTimeToLive(1);  
  26.             socket.joinGroup(iaddress);  
  27.         }catch(Exception e){  
  28.             e.printStackTrace();  
  29.         }  
  30.   
  31.     }  
  32.     @Override   //最简单的方法也就是建立一个线程来运行   
  33.     public void run(){  
  34.         while(true){  
  35.             byte[] data=weather.getBytes();  
  36.             DatagramPacket packet=new DatagramPacket(data,data.length,iaddress,port);  
  37.             //          System.out.println(weather);   
  38.             System.out.println(new String(data));  
  39.             try {  
  40.                 socket.send(packet);  
  41.                 sleep(3000);//线程休眠3秒   
  42.             } catch (Exception e) {  
  43.                 // TODO Auto-generated catch block   
  44.                 e.printStackTrace();  
  45.             }  
  46.         }  
  47.     }  
  48.     public static void main(String[] args){  
  49.         Weather w=new Weather();  
  50.         w.start();  
  51.     }  
  52. }  
This is the receive part.

[java]

  1. package com.han;  
  2. import java.awt.BorderLayout;  
  3. import java.awt.Color;  
  4. import java.awt.event.*;  
  5. import java.io.IOException;  
  6. import java.net.DatagramPacket;  
  7. import java.net.InetAddress;  
  8. import java.net.MulticastSocket;  
  9. import javax.swing.JButton;  
  10. import javax.swing.JFrame;  
  11. import javax.swing.JPanel;  
  12. import javax.swing.JScrollPane;  
  13. import javax.swing.JTextArea;  
  14. /** 
  15.  * This is the receive part. 
  16.  * @author HAN 
  17.  * 
  18.  */  
  19. public class Receive extends JFrame implements Runnable, ActionListener{  
  20.     private static final long serialVersionUID = 3362377947503474102L;  
  21.     int port=9898;  
  22.     InetAddress group;  
  23.     MulticastSocket socket; //socket sends and receives the packet.   
  24.     DatagramPacket packet;  
  25.     JButton ince=new JButton("开始接收");  
  26.     JButton stop=new JButton("停止接收");  
  27.     JTextArea inceAr=new JTextArea(10,20);  
  28.     JTextArea inced=new JTextArea(10,20);  
  29.     Thread thread;  
  30.     boolean b = false;  
  31.     byte[] buf=new byte[30];// If the message is longer than the packet's length, the message is truncated.   
  32.       
  33.     //在构造方法中设置具体参数特性,也就是初始化   
  34.     public Receive(){  
  35.         super("广播数据报");  
  36.         thread=new Thread(this);  
  37.         ince.addActionListener(this);  
  38.         stop.addActionListener(this);  
  39.         inceAr.setForeground(Color.blue);  
  40.         JPanel north=new JPanel();  
  41.         north.add(ince);  
  42.         north.add(stop);  
  43.         add(north,BorderLayout.NORTH);  
  44.         JPanel center=new JPanel();  
  45.         JScrollPane sp=new JScrollPane(inceAr);  
  46.         JScrollPane sp2=new JScrollPane(inced);  
  47.         inceAr.setLineWrap(true);  
  48.         inceAr.setEditable(false);  
  49.         inced.setLineWrap(true);  
  50.         inced.setEditable(false);  
  51.         center.add(sp);  
  52.         center.add(sp2);  
  53.         add(center,BorderLayout.CENTER);  
  54.         pack(); //JFrame inherited from Window   
  55.         validate();  
  56.         setVisible(true);  
  57.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
  58.         try {  
  59.             socket=new MulticastSocket(port);  
  60.             //A multicast group is specified by a class D IP address    
  61.             //and by a standard UDP port number.   
  62.             //Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive.   
  63.             //The address 224.0.0.0 is reserved and should not be used.   
  64.             group=InetAddress.getByName("233.0.0.0");  
  65.             socket.joinGroup(group);   
  66.             packet=new DatagramPacket(buf,buf.length);  
  67.               
  68.         } catch (IOException e) {  
  69.             // TODO Auto-generated catch block   
  70.             e.printStackTrace();  
  71.         }  
  72.           
  73.     }  
  74.     @Override  
  75.     public void run(){  
  76.         while(true){  
  77.             try {  
  78.                 socket.receive(packet);  
  79.             } catch (IOException e) {  
  80.                 // TODO Auto-generated catch block   
  81.                 e.printStackTrace();  
  82.             }  
  83. //          String message=new String(buf);   
  84.             String message=new String(packet.getData(),0,packet.getLength());//very important !!   
  85. //          System.out.println(message.length());   
  86.             inceAr.setText("正在接受的内容: \n"+message);  
  87.             inced.append(message+"\n");  
  88.             if(b==true){  
  89.                 break;  
  90.             }  
  91.         }  
  92.     }  
  93.     public void actionPerformed(ActionEvent e){  
  94.         Object object=e.getSource();  
  95.         if(object==ince){  
  96.             //If this thread is already on the state "run", do nothing.   
  97.             if(!thread.isAlive()){  
  98.                 thread=new Thread(this);  
  99.                 thread.start();  
  100.                 ince.setBackground(Color.red);  
  101.                 stop.setBackground(Color.yellow);  
  102.                 b=false;  
  103.             }     
  104.         }  
  105.         if(object==stop){  
  106.             ince.setBackground(Color.yellow);  
  107.             stop.setBackground(Color.red);  
  108.             b=true;  
  109.         }  
  110.     }  
  111.     public static void main(String[] args){  
  112.         @SuppressWarnings("unused")  
  113.         Receive rec=new Receive();  
  114. //      rec.setSize(460, 200);//提供了额外设置窗体大小的方式   
  115.     }  
  116. }  
这上面的程序运用了很多JAVA的核心技术以及很多需要注意的地方,可以堪称一个JAVA的精髓例子,记录下来以便以后查阅。

相关内容