UDP接收数据报

时间:2022-12-21 20:29:11

对于接受udp数据包,可以有如下另种设计:

第一,同UDP发送端一样,写成一个助手类,然后每次将收到的结果给需要的地方。

另一种是,将udp接收端与其处理程序写在同一个类中,即其受到数据之后就进行分析,然后做出判断与处理。

分析

对于本应用程序来说,我才去了第二中方法。首先,该udp接收端是在应用程序实例化是就存在,直到应用程序死亡期结束生命。那么从始至终我们只需要一个udp接受端。其次在设计udp接收端是,其接受的数据主要是字符串,对字符串做出相应处理的时间一般不会太长。而且UDP接收端接收到数据后要做出相应的操作,而且多数会用到调用它的类的相关方法。

实现

前面已将分析了,UDP接收端接收到数据后要做出相应的操作,而且多数会用到调用它的类的相关方法。所以udp接收端在实例化的时候,需要知道调用它的类的引用。

其次,接收端为阻塞方法,其应该单写在一个线程中。

代码实现

Java代码   UDP接收数据报
  1. package cn.edu.heut.zcl;  
  2.    
  3. import java.io.IOException;  
  4. import java.net.DatagramPacket;  
  5. import java.net.DatagramSocket;  
  6. import java.net.InetAddress;  
  7. import java.net.SocketException;  
  8. import java.net.UnknownHostException;  
  9. import java.util.regex.Matcher;  
  10. import java.util.regex.Pattern;  
  11.    
  12. import javax.swing.JOptionPane;  
  13.    
  14. import cn.edu.heut.helper.UDPSendHelper;  
  15. import cn.edu.heut.zcl.domain.UserInfo;  
  16. import cn.edu.heut.zcl.rtp.capture.AudioCapture;  
  17. import static cn.edu.heut.zcl.Constant.*;  
  18. /** 
  19.  * 该类主要是一直循环等待着其他客户端发来的消息,监听端口是19881 
  20.  * 发送端将采用广播的形式进行发送。 
  21.  * @author zcl 
  22.  * 
  23.  */  
  24. public class UDPReceiveSystemInfo extends Thread{  
  25.          /** 
  26.           * 大管家的引用 
  27.           */  
  28.          private Master master ;  
  29.          /** 
  30.           * 接收者的套接字 
  31.           */  
  32.          private DatagramSocket receiveSocket ;  
  33.          private DatagramPacket receiveDatagramPacket ;  
  34.          public UDPReceiveSystemInfo(Master master){  
  35.                    this.master = master ;  
  36.          }  
  37.           
  38.          @Override  
  39.          public void run() {  
  40.                    try {  
  41.                             receiveSocket = new DatagramSocket(UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT);  
  42.                    } catch (SocketException e) {  
  43.                             e.printStackTrace();  
  44.                    }  
  45.                    while(master.isLive()){//如果程序还在运行,那么就一直循环监听  
  46.                             receiveDatagramPacket = new DatagramPacket(  
  47.                                                new byte[UDPRECEIVESYSTEMINFO_UDP_RECEIVE_DP_LENGTH],UDPRECEIVESYSTEMINFO_UDP_RECEIVE_DP_LENGTH);  
  48.                             try {//此处接收发送来的数据报文  
  49.                                      receiveSocket.receive(receiveDatagramPacket);  
  50.                                      executeReceiveData(receiveDatagramPacket);  
  51.                                       
  52.                             } catch (IOException e) {  
  53.                                      e.printStackTrace();  
  54.                             }  
  55.                    }  
  56.                    if(!master.isLive()){  
  57.                             receiveSocket.close();  
  58.                              
  59.                    }  
  60.          }  
  61.           
  62.          /** 
  63.           * 处理发送来的数据 
  64.           * @param 发送来的数据 
  65.           */  
  66.          public void executeReceiveData(DatagramPacket receiveDP){  
  67.                    String receiveData = new String(receiveDP.getData()).trim();//得到发送过来的数据  
  68.                    String ipAddress = receiveDP.getAddress().getHostAddress();  
  69. //                 System.out.println("ipAddress::::::::  "+ipAddress);  
  70.                    if(receiveData.startsWith(CONTROL_MSG_ADD_A_CLIENT)){//如果是新添加一个客户端,执行以下操作  
  71.                             String name = findUserName(receiveData);  
  72.                             //将该客户端的信息添加到记录当前在线用户的list中  
  73.                             UserInfo newUser = new UserInfo();  
  74.                             newUser.setUserName(name);  
  75.                             newUser.setUserIP(receiveDP.getAddress());  
  76.                             master.currentOnLineUserList.add(newUser);  
  77.                             //在PhoneFrame的表格中添加该客户端信息。  
  78.                             String[] rowData = {name,ipAddress};  
  79.                             master.phoneFrame.defaultTableModel.addRow(rowData);  
  80.                             String localHostIP = null;  
  81.                             try {  
  82.                                      localHostIP = InetAddress.getLocalHost().toString();  
  83.                             } catch (UnknownHostException e) {  
  84.                                      e.printStackTrace();  
  85.                             }  
  86.                             //如果不是自己的话,之后再告诉这个新加入的客户端,我是谁,我的相关信息  
  87.                             if(!master.getUserName().equals(name) && !ipAddress.equals(localHostIP)){  
  88.                                      String data = CONTROL_MSG_ADD_A_CLIENT_ECHO_INFO +CONTROL_MSG_USER_NAEM +master.getUserName() + CONTROL_MSG_END_USER_NAEM;  
  89.                                      InetAddress destIPAddress = null;  
  90.                                      destIPAddress = receiveDP.getAddress();  
  91.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  92.                                      new UDPSendHelper(data, destIPAddress, destPort).start();  
  93.                             }  
  94.                              
  95.                    }else if(receiveData.startsWith(CONTROL_MSG_LEAVE_THE_CLIENT)){//收到退出一个客户端,执行以下方法  
  96. //                          System.out.println(receiveData);  
  97.                             String name = findUserName(receiveData);  
  98.                             //将list中的该用户删除  
  99.                             for(int i=0 ;i<master.currentOnLineUserList.size();i++){  
  100.                                      UserInfo ui = master.currentOnLineUserList.get(i);  
  101.                                      String uiName = ui.getUserName();  
  102.                                      InetAddress uiIp = ui.getUserIP() ;  
  103.                                      if(uiName.equals(name) && uiIp.toString().equals(ipAddress)){//判断是否是同一个用户,删除该项,退出循环  
  104.                                                master.currentOnLineUserList.remove(i);  
  105.                                                break;  
  106.                                      }  
  107.                             }  
  108.                             //将PhoneFrame表格中的信息删除  
  109.                             for(int i=0 ;i<master.phoneFrame.defaultTableModel.getRowCount();i++){//进行行遍历  
  110.                                      String curTabUserName = (String) master.phoneFrame.defaultTableModel.getValueAt(i, 0);  
  111.                                      String curTabUserIP = (String) master.phoneFrame.defaultTableModel.getValueAt(i, 1);  
  112.                                      if(curTabUserName.equals(name) && curTabUserIP.equals(ipAddress)){  
  113.                                                master.phoneFrame.defaultTableModel.removeRow(i);  
  114.                                                break;  
  115.                                      }  
  116.                                       
  117.                             }  
  118.                    }else if(receiveData.startsWith(CONTROL_MSG_ADD_A_CLIENT_ECHO_INFO)){//如果是收到了该客户端发送给其他服务器的新添加一个客户端的回复信息,则根据回复信息,将该发送者信息添加入list,并且在表格中显示。  
  119.                             String name = findUserName(receiveData);  
  120.                             //将该客户端的信息添加到记录当前在线用户的list中  
  121.                             UserInfo newUser = new UserInfo();  
  122.                             newUser.setUserName(name);  
  123.                             newUser.setUserIP(receiveDP.getAddress());  
  124.                             master.currentOnLineUserList.add(newUser);  
  125.                             //在PhoneFrame的表格中添加该客户端信息。  
  126.                             String[] rowData = {name,ipAddress};  
  127.                             master.phoneFrame.defaultTableModel.addRow(rowData);  
  128.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_REQUEST)){//如果收到的进行语音通讯请求,执行以下内容  
  129.                             if(!master.connectState.isConnecting()){//如果当前客户端没有通话,则执行以下操作  
  130.                                       
  131.                                      System.out.println("receiveData request:"+receiveDP.getAddress().toString());  
  132.                                      int conJOP =JOptionPane.showConfirmDialog(null,ipAddress+"的来电,是否接听""来电",  
  133.                         JOptionPane.YES_NO_OPTION);  
  134.                                      InetAddress destAddress = receiveDP.getAddress();  
  135.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  136.                                      switch(conJOP){  
  137.                                      case 0://接听来电  
  138.                                                String acceptData = CONTROL_MSG_CONNECT_VOICE_ACCEPT;  
  139.                                                new UDPSendHelper(acceptData, destAddress, destPort).start();  
  140.                                                master.connectState.setConnecting(true);//设置当前连接为通话状态  
  141. //do something...  
  142. //                                             new AudioCapture(master,ipAddress).start();  
  143.                                                String port = RTP_CALLER_RECEIVE_VOICE_PORT;  
  144.                                                new Thread(new AudioCapture(master,ipAddress,port)).start();//开启通话线程开始通话  
  145.                                                break;  
  146.                                      case 1://拒绝来电  
  147.                                                String refuseData = CONTROL_MSG_CONNECT_VOICE_REFUSE;  
  148.                                                new UDPSendHelper(refuseData, destAddress, destPort).start();  
  149.                                                break;  
  150.                                      }  
  151.                                       
  152.                             }else{//如果当前客户端正在通话,则执行如下操作:告诉请求方,我正在通话,等会再打过来  
  153.                                       
  154.                                      String sendConnectingDate = CONTROL_MSG_STATE_CONNECTING;  
  155.                                      InetAddress destAddress = receiveDP.getAddress();  
  156.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  157.                                      new UDPSendHelper(sendConnectingDate, destAddress, destPort).start();  
  158.                             }  
  159.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_ACCEPT)){//刚刚发送的请求被接受。此为主叫方  
  160. //do something...  
  161.                             String port = RTP_CALLER_SEND_VOICE_PORT;  
  162.                             new Thread(new AudioCapture(master,ipAddress,port)).start();//开启通话线程开始通话  
  163.                             System.out.println("执行通话操作..");  
  164.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_REFUSE) ){//刚刚发送的请求被拒绝  
  165.                             JOptionPane.showConfirmDialog(null,ipAddress+"拒绝您的来电""拒绝来电",  
  166.                     JOptionPane.YES_OPTION);  
  167.                    }else if( receiveData.startsWith(CONTROL_MSG_STATE_CONNECTING)){//对方正在通话中,执行如下操作  
  168.                             JOptionPane.showConfirmDialog(null,ipAddress+"正在通话中,请稍后再拨""提示", JOptionPane.YES_OPTION);  
  169.                    }  
  170.                     
  171.          }  
  172.          /** 
  173.           * 从字符串str中寻找用户的用户名,如果存在返回用户名,不存在返回null。 
  174.           * -用户名是包裹在名字控制字符中间的字符串。 
  175.           * @param str 
  176.           * @return uName 返回用户名 
  177.           */  
  178.          public String findUserName(String str){  
  179.                    String uName = null ;  
  180.                    String msg =findFirstPatternString(CONTROL_MSG_USER_NAEM+"{1}.*"+CONTROL_MSG_END_USER_NAEM+"{1}", str);  
  181.                    uName = msg.substring(CONTROL_MSG_USER_NAEM.length(), msg.length()-CONTROL_MSG_END_USER_NAEM.length());//此处得到用户名字  
  182.                    return uName;  
  183.          }  
  184.           
  185.          /** 
  186.           * 查询msg中是否存在符合patternString的字符串,如果有返回第一个出现该字符串的数据,不存在返回null 
  187.           * @param patternString 匹配字符串 
  188.           * @param msg 查询字符串 
  189.           * @return 结果 
  190.           */  
  191.          public static String findFirstPatternString(String patternString,String msg){  
  192.                    String result  = null ;  
  193.                    Pattern p = Pattern.compile(patternString);  
  194.                    Matcher m = p.matcher(msg);  
  195.                    if(m.find()){  
  196.                             result = m.group();  
  197.                    }  
  198.                    return result;  
  199.          }  
  200.           
  201.           
  202.           
  203. }  
 

以上是udp接收端的代码,一种会有一些类暂时还没有给出,在之后会介绍到。代码也会随程序中其他代码一起给出。