1. 程式人生 > >UDP接收資料報

UDP接收資料報

對於接受udp資料包,可以有如下另種設計:

第一,同UDP傳送端一樣,寫成一個助手類,然後每次將收到的結果給需要的地方。

另一種是,將udp接收端與其處理程式寫在同一個類中,即其受到資料之後就進行分析,然後做出判斷與處理。

分析

對於本應用程式來說,我才去了第二中方法。首先,該udp接收端是在應用程式例項化是就存在,直到應用程式死亡期結束生命。那麼從始至終我們只需要一個udp接受端。其次在設計udp接收端是,其接受的資料主要是字串,對字串做出相應處理的時間一般不會太長。而且UDP接收端接收到資料後要做出相應的操作,而且多數會用到呼叫它的類的相關方法。

實現

前面已將分析了,UDP接收端接收到資料後要做出相應的操作,而且多數會用到呼叫它的類的相關方法。所以udp接收端在例項化的時候,需要知道呼叫它的類的引用。

其次,接收端為阻塞方法,其應該單寫在一個執行緒中。

程式碼實現

Java程式碼  收藏程式碼
  1. package cn.edu.heut.zcl;  
  2. import java.io.IOException;  
  3. import java.net.DatagramPacket;  
  4. import java.net.DatagramSocket;  
  5. import java.net.InetAddress;  
  6. import java.net.SocketException;  
  7. import java.net.UnknownHostException;  
  8. import java.util.regex.Matcher;  
  9. import java.util.regex.Pattern;  
  10. import javax.swing.JOptionPane;  
  11. import cn.edu.heut.helper.UDPSendHelper;  
  12. import cn.edu.heut.zcl.domain.UserInfo;  
  13. import cn.edu.heut.zcl.rtp.capture.AudioCapture;  
  14. import static cn.edu.heut.zcl.Constant.*;  
  15. /** 
  16.  * 該類主要是一直迴圈等待著其他客戶端發來的訊息,監聽埠是19881 
  17.  * 傳送端將採用廣播的形式進行傳送。
     
  18.  * @author zcl 
  19.  * 
  20.  */  
  21. public class UDPReceiveSystemInfo extends Thread{  
  22.          /** 
  23.           * 大管家的引用 
  24.           */  
  25.          private Master master ;  
  26.          /** 
  27.           * 接收者的套接字 
  28.           */  
  29.          private DatagramSocket receiveSocket ;  
  30.          private DatagramPacket receiveDatagramPacket ;  
  31.          public UDPReceiveSystemInfo(Master master){  
  32.                    this.master = master ;  
  33.          }  
  34.          @Override  
  35.          public void run() {  
  36.                    try {  
  37.                             receiveSocket = new DatagramSocket(UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT);  
  38.                    } catch (SocketException e) {  
  39.                             e.printStackTrace();  
  40.                    }  
  41.                    while(master.isLive()){//如果程式還在執行,那麼就一直迴圈監聽  
  42.                             receiveDatagramPacket = new DatagramPacket(  
  43.                                                new byte[UDPRECEIVESYSTEMINFO_UDP_RECEIVE_DP_LENGTH],UDPRECEIVESYSTEMINFO_UDP_RECEIVE_DP_LENGTH);  
  44.                             try {//此處接收發送來的資料報文  
  45.                                      receiveSocket.receive(receiveDatagramPacket);  
  46.                                      executeReceiveData(receiveDatagramPacket);  
  47.                             } catch (IOException e) {  
  48.                                      e.printStackTrace();  
  49.                             }  
  50.                    }  
  51.                    if(!master.isLive()){  
  52.                             receiveSocket.close();  
  53.                    }  
  54.          }  
  55.          /** 
  56.           * 處理髮送來的資料 
  57.           * @param 傳送來的資料 
  58.           */  
  59.          public void executeReceiveData(DatagramPacket receiveDP){  
  60.                    String receiveData = new String(receiveDP.getData()).trim();//得到傳送過來的資料  
  61.                    String ipAddress = receiveDP.getAddress().getHostAddress();  
  62. //                 System.out.println("ipAddress::::::::  "+ipAddress);  
  63.                    if(receiveData.startsWith(CONTROL_MSG_ADD_A_CLIENT)){//如果是新新增一個客戶端,執行以下操作  
  64.                             String name = findUserName(receiveData);  
  65.                             //將該客戶端的資訊新增到記錄當前線上使用者的list中  
  66.                             UserInfo newUser = new UserInfo();  
  67.                             newUser.setUserName(name);  
  68.                             newUser.setUserIP(receiveDP.getAddress());  
  69.                             master.currentOnLineUserList.add(newUser);  
  70.                             //在PhoneFrame的表格中新增該客戶端資訊。  
  71.                             String[] rowData = {name,ipAddress};  
  72.                             master.phoneFrame.defaultTableModel.addRow(rowData);  
  73.                             String localHostIP = null;  
  74.                             try {  
  75.                                      localHostIP = InetAddress.getLocalHost().toString();  
  76.                             } catch (UnknownHostException e) {  
  77.                                      e.printStackTrace();  
  78.                             }  
  79.                             //如果不是自己的話,之後再告訴這個新加入的客戶端,我是誰,我的相關資訊  
  80.                             if(!master.getUserName().equals(name) && !ipAddress.equals(localHostIP)){  
  81.                                      String data = CONTROL_MSG_ADD_A_CLIENT_ECHO_INFO +CONTROL_MSG_USER_NAEM +master.getUserName() + CONTROL_MSG_END_USER_NAEM;  
  82.                                      InetAddress destIPAddress = null;  
  83.                                      destIPAddress = receiveDP.getAddress();  
  84.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  85.                                      new UDPSendHelper(data, destIPAddress, destPort).start();  
  86.                             }  
  87.                    }else if(receiveData.startsWith(CONTROL_MSG_LEAVE_THE_CLIENT)){//收到退出一個客戶端,執行以下方法  
  88. //                          System.out.println(receiveData);  
  89.                             String name = findUserName(receiveData);  
  90.                             //將list中的該使用者刪除  
  91.                             for(int i=0 ;i<master.currentOnLineUserList.size();i++){  
  92.                                      UserInfo ui = master.currentOnLineUserList.get(i);  
  93.                                      String uiName = ui.getUserName();  
  94.                                      InetAddress uiIp = ui.getUserIP() ;  
  95.                                      if(uiName.equals(name) && uiIp.toString().equals(ipAddress)){//判斷是否是同一個使用者,刪除該項,退出迴圈  
  96.                                                master.currentOnLineUserList.remove(i);  
  97.                                                break;  
  98.                                      }  
  99.                             }  
  100.                             //將PhoneFrame表格中的資訊刪除  
  101.                             for(int i=0 ;i<master.phoneFrame.defaultTableModel.getRowCount();i++){//進行行遍歷  
  102.                                      String curTabUserName = (String) master.phoneFrame.defaultTableModel.getValueAt(i, 0);  
  103.                                      String curTabUserIP = (String) master.phoneFrame.defaultTableModel.getValueAt(i, 1);  
  104.                                      if(curTabUserName.equals(name) && curTabUserIP.equals(ipAddress)){  
  105.                                                master.phoneFrame.defaultTableModel.removeRow(i);  
  106.                                                break;  
  107.                                      }  
  108.                             }  
  109.                    }else if(receiveData.startsWith(CONTROL_MSG_ADD_A_CLIENT_ECHO_INFO)){//如果是收到了該客戶端傳送給其他伺服器的新新增一個客戶端的回覆資訊,則根據回覆資訊,將該傳送者資訊新增入list,並且在表格中顯示。  
  110.                             String name = findUserName(receiveData);  
  111.                             //將該客戶端的資訊新增到記錄當前線上使用者的list中  
  112.                             UserInfo newUser = new UserInfo();  
  113.                             newUser.setUserName(name);  
  114.                             newUser.setUserIP(receiveDP.getAddress());  
  115.                             master.currentOnLineUserList.add(newUser);  
  116.                             //在PhoneFrame的表格中新增該客戶端資訊。  
  117.                             String[] rowData = {name,ipAddress};  
  118.                             master.phoneFrame.defaultTableModel.addRow(rowData);  
  119.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_REQUEST)){//如果收到的進行語音通訊請求,執行以下內容  
  120.                             if(!master.connectState.isConnecting()){//如果當前客戶端沒有通話,則執行以下操作  
  121.                                      System.out.println("receiveData request:"+receiveDP.getAddress().toString());  
  122.                                      int conJOP =JOptionPane.showConfirmDialog(null,ipAddress+"的來電,是否接聽""來電",  
  123.                         JOptionPane.YES_NO_OPTION);  
  124.                                      InetAddress destAddress = receiveDP.getAddress();  
  125.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  126.                                      switch(conJOP){  
  127.                                      case 0://接聽來電  
  128.                                                String acceptData = CONTROL_MSG_CONNECT_VOICE_ACCEPT;  
  129.                                                new UDPSendHelper(acceptData, destAddress, destPort).start();  
  130.                                                master.connectState.setConnecting(true);//設定當前連線為通話狀態  
  131. //do something...  
  132. //                                             new AudioCapture(master,ipAddress).start();  
  133.                                                String port = RTP_CALLER_RECEIVE_VOICE_PORT;  
  134.                                                new Thread(new AudioCapture(master,ipAddress,port)).start();//開啟通話執行緒開始通話  
  135.                                                break;  
  136.                                      case 1://拒絕來電  
  137.                                                String refuseData = CONTROL_MSG_CONNECT_VOICE_REFUSE;  
  138.                                                new UDPSendHelper(refuseData, destAddress, destPort).start();  
  139.                                                break;  
  140.                                      }  
  141.                             }else{//如果當前客戶端正在通話,則執行如下操作:告訴請求方,我正在通話,等會再打過來  
  142.                                      String sendConnectingDate = CONTROL_MSG_STATE_CONNECTING;  
  143.                                      InetAddress destAddress = receiveDP.getAddress();  
  144.                                      int destPort = UDPRECEIVESYSTEMINFO_UDP_RECEIVE_PORT;  
  145.                                      new UDPSendHelper(sendConnectingDate, destAddress, destPort).start();  
  146.                             }  
  147.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_ACCEPT)){//剛剛傳送的請求被接受。此為主叫方  
  148. //do something...  
  149.                             String port = RTP_CALLER_SEND_VOICE_PORT;  
  150.                             new Thread(new AudioCapture(master,ipAddress,port)).start();//開啟通話執行緒開始通話  
  151.                             System.out.println("執行通話操作..");  
  152.                    }else if(receiveData.startsWith(CONTROL_MSG_CONNECT_VOICE_REFUSE) ){//剛剛傳送的請求被拒絕  
  153.                             JOptionPane.showConfirmDialog(null,ipAddress+"拒絕您的來電""拒絕來電",  
  154.                     JOptionPane.YES_OPTION);  
  155.                    }else if( receiveData.startsWith(CONTROL_MSG_STATE_CONNECTING)){//對方正在通話中,執行如下操作  
  156.                             JOptionPane.showConfirmDialog(null,ipAddress+"正在通話中,請稍後再撥""提示", JOptionPane.YES_OPTION);  
  157.                    }  
  158.          }  
  159.          /** 
  160.           * 從字串str中尋找使用者的使用者名稱,如果存在返回使用者名稱,不存在返回null。 
  161.           * -使用者名稱是包裹在名字控制字元中間的字串。 
  162.           * @param str 
  163.           * @return uName 返回使用者名稱 
  164.           */  
  165.          public String findUserName(String str){  
  166.                    String uName = null ;  
  167.                    String msg =findFirstPatternString(CONTROL_MSG_USER_NAEM+"{1}.*"+CONTROL_MSG_END_USER_NAEM+"{1}", str);  
  168.                    uName = msg.substring(CONTROL_MSG_USER_NAEM.length(), msg.length()-CONTROL_MSG_END_USER_NAEM.length());//此處得到使用者名稱字  
  169.                    return uName;  
  170.          }  
  171.          /** 
  172.           * 查詢msg中是否存在符合patternString的字串,如果有返回第一個出現該字串的資料,不存在返回null 
  173.           * @param patternString 匹配字串 
  174.           * @param msg 查詢字串 
  175.           * @return 結果 
  176.           */  
  177.          public static String findFirstPatternString(String patternString,String msg){  
  178.                    String result  = null ;  
  179.                    Pattern p = Pattern.compile(patternString);  
  180.                    Matcher m = p.matcher(msg);  
  181.                    if(m.find()){  
  182.                             result = m.group();  
  183.                    }  
  184.                    return result;  
  185.          }  
  186. }  
 

以上是udp接收端的程式碼,一種會有一些類暫時還沒有給出,在之後會介紹到。程式碼也會隨程式中其他程式碼一起給出。