java udp 广播

来源:互联网 发布:php调用lua 编辑:程序博客网 时间:2024/04/29 22:51

udp 是一种网络通信协议,不需要客户端和服务器端建立连接即可进行通讯功能。相对于Tcp协议它有着tcp用很多优点,例如广播功能。udp的广播功能可以指定特定网段进行广播内容,而无需知道接收者是谁,只有接受者在广播范围内即可接收广播内容。其实基于这个功能可以实现一个局域网群聊室的功能。

udp广播发送有两种形式,

方式一:通过DatagramSocket实现

方式二:通过MulticastSocket 实现


方式一:demo;


1,数据发送端:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.net.DatagramPacket;  
  3. import java.net.DatagramSocket;  
  4. import java.net.InetAddress;  
  5. import java.net.SocketException;  
  6. import java.net.UnknownHostException;  
  7.   
  8.   
  9. public class SendIP {  
  10.   
  11.     public static void main(String args[]) {  
  12.         new SendIP().lanchApp();  
  13.      }  
  14.       
  15.     private void lanchApp(){  
  16.         SendThread th=new SendThread();  
  17.         th.start();  
  18.     }  
  19.       
  20.       
  21.     private class SendThread extends Thread{  
  22.         @Override  
  23.         public void run() {  
  24.             while(true){  
  25.                 try {  
  26.                     Thread.sleep(1000);  
  27.                 } catch (InterruptedException e) {  
  28.                     e.printStackTrace();  
  29.                 }  
  30.                 try {  
  31.                     BroadcastIP();  
  32.                 } catch (Exception e) {  
  33.                     e.printStackTrace();  
  34.                 }  
  35.             }  
  36.         }  
  37.           
  38.         private void BroadcastIP()throws Exception{  
  39.              DatagramSocket dgSocket=new DatagramSocket();  
  40.               byte b[]="你好,这是我发给你的消息".getBytes();  
  41.               DatagramPacket dgPacket=new DatagramPacket(b,b.length,InetAddress.getByName("255.255.255.255"),8989);  
  42.               dgSocket.send(dgPacket);  
  43.               dgSocket.close();  
  44.               System.out.println("send message is ok.");  
  45.         }  
  46.     }  
  47.       
  48. }  

2,数据接收端:

[java] view plaincopy
  1. import java.net.DatagramPacket;  
  2. import java.net.DatagramSocket;  
  3. import java.net.SocketException;  
  4. import java.util.regex.Matcher;  
  5. import java.util.regex.Pattern;  
  6.   
  7.     public class SearchIP{  
  8.           
  9.          public static void main(String args[])throws Exception{  
  10.            
  11.              new SearchIP().lanchApp();  
  12.          }  
  13.            
  14.          private void lanchApp(){  
  15.              receiveThread th=new receiveThread();  
  16.                 th.start();  
  17.             }  
  18.            
  19.          private class receiveThread extends Thread{  
  20.              @Override  
  21.                 public void run() {  
  22.                     while(true){  
  23.                         try {  
  24.                             Thread.sleep(1000);  
  25.                         } catch (InterruptedException e) {  
  26.                             e.printStackTrace();  
  27.                         }  
  28.                         try {  
  29.                             receiveIP();  
  30.                         } catch (Exception e) {  
  31.                             e.printStackTrace();  
  32.                         }  
  33.                     }  
  34.              }  
  35.                
  36.             private void receiveIP() throws Exception{  
  37.                  DatagramSocket dgSocket=new DatagramSocket(8989);  
  38.                   byte[] by=new byte[1024];  
  39.                   DatagramPacket packet=new DatagramPacket(by,by.length);  
  40.                   dgSocket.receive(packet);  
  41.                     
  42.                   String str=new String(packet.getData(),0,packet.getLength());  
  43.                     
  44.                   System.out.println("接收到数据大小:"+str.length());  
  45.                   System.out.println("接收到的数据为:"+str);  
  46.                   dgSocket.close();  
  47.                   System.out.println("recevied message is ok.");  
  48.              }  
  49.          }  
  50.   
  51.                
  52.     }  


方式二demo;


1,数据发送端:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.net.DatagramPacket;  
  3. import java.net.InetAddress;  
  4. import java.net.MulticastSocket;  
  5.   
  6.   
  7. public class MulBroadcast extends Thread{  
  8.   
  9.     String info ="节目预告: 恭喜您中500w彩票了";    
  10.     int port =9898;    
  11.     InetAddress address;  
  12.     MulticastSocket socket;    
  13.       
  14.    public MulBroadcast(){  
  15.        try{  
  16.        address=InetAddress.getByName("233.0.0.0");    
  17.        socket=new MulticastSocket(port);    
  18.        socket.setTimeToLive(1);    
  19.        socket.joinGroup(address);    
  20.        }catch(IOException e){  
  21.            e.printStackTrace();  
  22.        }  
  23.     }  
  24.      
  25.     @Override   //最简单的方法也就是建立一个线程来运行     
  26.     public void run(){    
  27.         while(true){    
  28.             byte[] data=info.getBytes();    
  29.             DatagramPacket packet=new DatagramPacket(data,data.length,address,port);    
  30.               
  31.             try {    
  32.                 socket.send(packet);   
  33.                 Thread.sleep(3000);  
  34.             } catch (Exception e) {    
  35.                 e.printStackTrace();    
  36.             }    
  37.             System.out.println("消息已发送:");    
  38.         }    
  39.     }    
  40.       
  41.     public static void main(String[] args){    
  42.         new MulBroadcast().start();  
  43.     }    
  44.       
  45. }  

2,数据接收端:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.net.DatagramPacket;  
  3. import java.net.InetAddress;  
  4. import java.net.MulticastSocket;  
  5.   
  6.   
  7. public class MulReceiverIP extends Thread{  
  8.   
  9.         int port=9898;    
  10.         InetAddress group;    
  11.         MulticastSocket socket; //socket sends and receives the packet.     
  12.         DatagramPacket packet;   
  13.         byte[] buf=new byte[30];// If the message is longer than the packet's length, the message is truncated.  
  14.           
  15.     public MulReceiverIP(){  
  16.          try {    
  17.                 socket=new MulticastSocket(port);  
  18.                 
  19.                 group=InetAddress.getByName("233.0.0.0");   
  20.                 socket.joinGroup(group);    //加入广播组,加入group后,socket发送的数据报,可以被加入到group中的成员接收到。  
  21.                 packet=new DatagramPacket(buf,buf.length);    
  22.                     
  23.             } catch (IOException e) {    
  24.                 e.printStackTrace();    
  25.             }    
  26.     }  
  27.       
  28.       @Override    
  29.         public void run(){    
  30.             while(true){    
  31.                 try {    
  32.                     socket.receive(packet);    
  33.                 } catch (IOException e) {    
  34.                     e.printStackTrace();    
  35.                 }    
  36.                 //      String message=new String(buf);     
  37.                String message=new String(packet.getData(),0,packet.getLength());//very important !!     
  38.                System.out.println("接受消息内容: "+message);  
  39.                  
  40.             }    
  41.         }    
  42.         
  43.       public static void main(String[] args) {  
  44.             new MulReceiverIP().start();  
  45.     }  
  46.         
  47. }  
0 0
原创粉丝点击