免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Android實現(xiàn)TCP與UDP傳輸
2013-10-29 23:44 3653人閱讀 評論(0) 收藏 舉報
分類:

關于TCP和UDP協(xié)議的描述,可參考http://zhoujianghai.iteye.com/blog/1052970

 

下面是android與PC端使用TCP和UDP協(xié)議通信的例子:

以PC端作為服務器,android端使用TCP協(xié)議與服務器建立連接,使用UDP協(xié)議接受和發(fā)送數(shù)據(jù)。

服務器端代碼:

ThunderServer.java

 

Java代碼 
 
  1. package com.zhoujh.thunder.server;   
  2.   
  3. import java.io.DataOutputStream;   
  4. import java.io.IOException;   
  5. import java.net.DatagramPacket;   
  6. import java.net.DatagramSocket;   
  7. import java.net.InetSocketAddress;   
  8. import java.net.ServerSocket;   
  9. import java.net.Socket;   
  10. import java.net.SocketException;   
  11. import java.util.ArrayList;   
  12.   
  13. /**  
  14.  * 服務器端  
  15.  * @author   
  16.  * zhoujianghai  
  17.  * 2011-5-15  
  18.  * 下午05:10:50  
  19.  */  
  20. public class ThunderServer{   
  21.     private static int ID = 1;   
  22.        
  23.     /**TCP端口 */  
  24.     private static final int TCP_PORT = 8000;   
  25.     /**UDP端口 */  
  26.     private static final int UDP_PORT = 9999;   
  27.        
  28.        
  29.     /**與服務器已經(jīng)建立鏈接的客戶端數(shù)量 */  
  30.     private ArrayList<Client> clients = new ArrayList<Client>();   
  31.        
  32.     public static void main(String args[]) {   
  33.         new ThunderServer().start();   
  34.     }   
  35.   
  36.     private void start() {   
  37.         new UDPThread().start();   
  38.         ServerSocket serverSocket = null;   
  39.   
  40.         try {   
  41.             serverSocket = new ServerSocket(TCP_PORT);   
  42.         } catch (IOException e) {   
  43.             e.printStackTrace();   
  44.         }   
  45.         while (true) {   
  46.             Socket socket = null;   
  47.             try {   
  48.                 socket = serverSocket.accept();   
  49.                 System.out.println("socket="+socket);   
  50.                    
  51.                
  52.                 String IP = socket.getInetAddress().getHostAddress();   
  53.                 Client c = new Client(IP);     
  54.                 clients.add(c);   
  55.                    
  56.                 DataOutputStream out = new DataOutputStream(socket.getOutputStream());   
  57.                 out.writeInt(ID++);   
  58.                    
  59.                 System.out.println("一個新的客戶端已連接,IP:"+IP+";port="+socket.getPort()+"; ID="+(ID-1));   
  60.             } catch (IOException e) {   
  61.                 e.printStackTrace();   
  62.             }finally{   
  63.                 if(socket != null) {   
  64.                     try {   
  65.                         socket.close();   
  66.                         socket = null;   
  67.                     } catch (IOException e) {   
  68.                         // TODO Auto-generated catch block   
  69.                         e.printStackTrace();   
  70.                     }   
  71.                 }   
  72.             }   
  73.         }   
  74.            
  75.     }   
  76.        
  77.     /**  
  78.      * 客戶端:ip地址和udp端口  
  79.      * @author   
  80.      * zhoujianghai  
  81.      * 2011-5-15  
  82.      * 下午04:41:09  
  83.      */  
  84.     private class Client {   
  85.         String IP;   
  86.         int udpPort;   
  87.   
  88.         public Client(String IP) {   
  89.             this.IP = IP;   
  90.         }   
  91.         public void setUdpPort(int udpPort) {   
  92.             this.udpPort = udpPort;   
  93.         }   
  94.     }   
  95.        
  96.     /**  
  97.      * 接收客戶端發(fā)送的數(shù)據(jù),并把接收到的數(shù)據(jù)發(fā)送給所有客戶端,使用UDP協(xié)議  
  98.      * @author   
  99.      * zhoujianghai  
  100.      * 2011-5-15  
  101.      * 下午04:54:03  
  102.      */  
  103.     private class UDPThread extends Thread {   
  104.         //服務器每次收發(fā)數(shù)據(jù)的緩沖區(qū),大小是1024個字節(jié)   
  105.         byte[] buf = new byte[1024];   
  106.            
  107.         public void run() {   
  108.             DatagramSocket ds = null;   
  109.             try {   
  110.                 ds = new DatagramSocket(UDP_PORT);   
  111.             } catch (SocketException e) {   
  112.                 // TODO Auto-generated catch block   
  113.                 e.printStackTrace();   
  114.             }   
  115.                
  116.             while(ds != null) {   
  117.                 DatagramPacket packet = new DatagramPacket(buf, buf.length);   
  118.   
  119.                 try {   
  120.                     //接收數(shù)據(jù)包   
  121.                     ds.receive(packet);   
  122.                     System.out.println("地址:"+packet.getAddress()+"  端口:"+packet.getPort()+"數(shù)據(jù):"+new String(packet.getData()));   
  123.                     String clientIp =  (packet.getAddress().toString().split("/")[1]);   
  124.                     for(Client c:clients) {   
  125.                            
  126.                         if(clientIp.trim().equals(c.IP) && c.udpPort == 0) {   
  127.                             c.setUdpPort(packet.getPort());   
  128.                         }   
  129.                     }   
  130.                     //把接收到的數(shù)據(jù)包發(fā)送給所有已連接的客戶端   
  131.                     System.out.println("clients.size="+clients.size());   
  132.                     for(Client c:clients) {   
  133.                         System.out.println("server send:IP="+c.IP+"; udpPort="+c.udpPort);   
  134.                         //設置數(shù)據(jù)包要發(fā)送的客戶端地址   
  135.                         packet.setSocketAddress(new InetSocketAddress(c.IP, c.udpPort));   
  136.                         ds.send(packet);   
  137.                     }   
  138.                 } catch (IOException e) {   
  139.                     e.printStackTrace();   
  140.                 }   
  141.             }   
  142.         }   
  143.     }   
  144.        
  145. }  
  1. package com.zhoujh.thunder.server;  
  2.   
  3. import java.io.DataOutputStream;  
  4. import java.io.IOException;  
  5. import java.net.DatagramPacket;  
  6. import java.net.DatagramSocket;  
  7. import java.net.InetSocketAddress;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10. import java.net.SocketException;  
  11. import java.util.ArrayList;  
  12.   
  13. /** 
  14.  * 服務器端 
  15.  * @author  
  16.  * zhoujianghai 
  17.  * 2011-5-15 
  18.  * 下午05:10:50 
  19.  */  
  20. public class ThunderServer{  
  21.     private static int ID = 1;  
  22.       
  23.     /**TCP端口 */  
  24.     private static final int TCP_PORT = 8000;  
  25.     /**UDP端口 */  
  26.     private static final int UDP_PORT = 9999;  
  27.       
  28.       
  29.     /**與服務器已經(jīng)建立鏈接的客戶端數(shù)量 */  
  30.     private ArrayList<Client> clients = new ArrayList<Client>();  
  31.       
  32.     public static void main(String args[]) {  
  33.         new ThunderServer().start();  
  34.     }  
  35.   
  36.     private void start() {  
  37.         new UDPThread().start();  
  38.         ServerSocket serverSocket = null;  
  39.   
  40.         try {  
  41.             serverSocket = new ServerSocket(TCP_PORT);  
  42.         } catch (IOException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.         while (true) {  
  46.             Socket socket = null;  
  47.             try {  
  48.                 socket = serverSocket.accept();  
  49.                 System.out.println("socket="+socket);  
  50.                   
  51.               
  52.                 String IP = socket.getInetAddress().getHostAddress();  
  53.                 Client c = new Client(IP);    
  54.                 clients.add(c);  
  55.                   
  56.                 DataOutputStream out = new DataOutputStream(socket.getOutputStream());  
  57.                 out.writeInt(ID++);  
  58.                   
  59.                 System.out.println("一個新的客戶端已連接,IP:"+IP+";port="+socket.getPort()+"; ID="+(ID-1));  
  60.             } catch (IOException e) {  
  61.                 e.printStackTrace();  
  62.             }finally{  
  63.                 if(socket != null) {  
  64.                     try {  
  65.                         socket.close();  
  66.                         socket = null;  
  67.                     } catch (IOException e) {  
  68.                         // TODO Auto-generated catch block  
  69.                         e.printStackTrace();  
  70.                     }  
  71.                 }  
  72.             }  
  73.         }  
  74.           
  75.     }  
  76.       
  77.     /** 
  78.      * 客戶端:ip地址和udp端口 
  79.      * @author  
  80.      * zhoujianghai 
  81.      * 2011-5-15 
  82.      * 下午04:41:09 
  83.      */  
  84.     private class Client {  
  85.         String IP;  
  86.         int udpPort;  
  87.   
  88.         public Client(String IP) {  
  89.             this.IP = IP;  
  90.         }  
  91.         public void setUdpPort(int udpPort) {  
  92.             this.udpPort = udpPort;  
  93.         }  
  94.     }  
  95.       
  96.     /** 
  97.      * 接收客戶端發(fā)送的數(shù)據(jù),并把接收到的數(shù)據(jù)發(fā)送給所有客戶端,使用UDP協(xié)議 
  98.      * @author  
  99.      * zhoujianghai 
  100.      * 2011-5-15 
  101.      * 下午04:54:03 
  102.      */  
  103.     private class UDPThread extends Thread {  
  104.         //服務器每次收發(fā)數(shù)據(jù)的緩沖區(qū),大小是1024個字節(jié)  
  105.         byte[] buf = new byte[1024];  
  106.           
  107.         public void run() {  
  108.             DatagramSocket ds = null;  
  109.             try {  
  110.                 ds = new DatagramSocket(UDP_PORT);  
  111.             } catch (SocketException e) {  
  112.                 // TODO Auto-generated catch block  
  113.                 e.printStackTrace();  
  114.             }  
  115.               
  116.             while(ds != null) {  
  117.                 DatagramPacket packet = new DatagramPacket(buf, buf.length);  
  118.   
  119.                 try {  
  120.                     //接收數(shù)據(jù)包  
  121.                     ds.receive(packet);  
  122.                     System.out.println("地址:"+packet.getAddress()+"  端口:"+packet.getPort()+"數(shù)據(jù):"+new String(packet.getData()));  
  123.                     String clientIp =  (packet.getAddress().toString().split("/")[1]);  
  124.                     for(Client c:clients) {  
  125.                           
  126.                         if(clientIp.trim().equals(c.IP) && c.udpPort == 0) {  
  127.                             c.setUdpPort(packet.getPort());  
  128.                         }  
  129.                     }  
  130.                     //把接收到的數(shù)據(jù)包發(fā)送給所有已連接的客戶端  
  131.                     System.out.println("clients.size="+clients.size());  
  132.                     for(Client c:clients) {  
  133.                         System.out.println("server send:IP="+c.IP+"; udpPort="+c.udpPort);  
  134.                         //設置數(shù)據(jù)包要發(fā)送的客戶端地址  
  135.                         packet.setSocketAddress(new InetSocketAddress(c.IP, c.udpPort));  
  136.                         ds.send(packet);  
  137.                     }  
  138.                 } catch (IOException e) {  
  139.                     e.printStackTrace();  
  140.                 }  
  141.             }  
  142.         }  
  143.     }  
  144.       
  145. }  
 

客戶端的核心代碼:

 

public void connectServer(String IP,int port) {

Java代碼 
 
  1. this.IP = IP;   
  2.   
  3. try {   
  4.     socket = new DatagramSocket(udpPort);   
  5. catch (SocketException e) {   
  6.     e.printStackTrace();   
  7. }   
  8.   
  9. Socket s = null;   
  10. try {   
  11.     s = new Socket(IP,port);   
  12.     System.out.println("s="+s);   
  13.        
  14.     DataInputStream dis = new DataInputStream(s.getInputStream());   
  15.     int id = dis.readInt();   
  16.     System.out.println("id="+id);   
  17.   
  18. catch (UnknownHostException e) {   
  19.     // TODO Auto-generated catch block   
  20.     e.printStackTrace();   
  21. catch (IOException e) {   
  22.     e.printStackTrace();   
  23. }finally {   
  24.     if(s != null) {   
  25.         try {   
  26.             s.close();   
  27.             s = null;   
  28.         } catch (IOException e) {   
  29.             // TODO Auto-generated catch block   
  30.             e.printStackTrace();   
  31.         }   
  32.     }   
  33. }   
  1. this.IP = IP;  
  2.   
  3. try {  
  4.     socket = new DatagramSocket(udpPort);  
  5. catch (SocketException e) {  
  6.     e.printStackTrace();  
  7. }  
  8.   
  9. Socket s = null;  
  10. try {  
  11.     s = new Socket(IP,port);  
  12.     System.out.println("s="+s);  
  13.       
  14.     DataInputStream dis = new DataInputStream(s.getInputStream());  
  15.     int id = dis.readInt();  
  16.     System.out.println("id="+id);  
  17.   
  18. catch (UnknownHostException e) {  
  19.     // TODO Auto-generated catch block  
  20.     e.printStackTrace();  
  21. catch (IOException e) {  
  22.     e.printStackTrace();  
  23. }finally {  
  24.     if(s != null) {  
  25.         try {  
  26.             s.close();  
  27.             s = null;  
  28.         } catch (IOException e) {  
  29.             // TODO Auto-generated catch block  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33. }  
 

 

客戶端代碼綁定的UDP端口”udpPort“跟服務器端接收到的不一樣,為了避免了使用UDP通信時,android客戶端接收不到server發(fā)送的數(shù)據(jù)的問題,server端根據(jù)接收到的數(shù)據(jù)得出發(fā)送數(shù)據(jù)包的客戶端的ip地址和端口,不需要進行端口的轉(zhuǎn)發(fā),真機和模擬器一樣。代碼:

 

Java代碼 
 
  1. String clientIp =  (packet.getAddress().toString().split("/")[1]);   
  2.                     for(Client c:clients) {   
  3.                            
  4.                         if(clientIp.trim().equals(c.IP) && c.udpPort == 0) {   
  5.                             c.setUdpPort(packet.getPort());   
  6.                         }   
  7.                     }  
0
0
本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
手機移動平臺的視頻通訊系統(tǒng)
類 QQ IM 通訊軟件開發(fā)實戰(zhàn)
為什么聊天軟件一般采用UDP協(xié)議
第38講:TCP、UDP網(wǎng)絡編程
TCP和UDP數(shù)據(jù)包結構
TCP狀態(tài)知識總結(圖解)
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服