Android实现TCP与UDP传输

关于TCP和UDP协议的描述,可参考http://zhoujianghai.iteye.com/blog/1052970

 

下面是android与PC端使用TCP和UDP协议通信的例子:

以PC端作为服务器,android端使用TCP协议与服务器建立连接,使用UDP协议接受和发送数据。

服务器端代码:

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.     /**与服务器已经建立链接的客户端数量 */  
  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.      * 接收客户端发送的数据,并把接收到的数据发送给所有客户端,使用UDP协议  
  98.      * @author   
  99.      * zhoujianghai  
  100.      * 2011-5-15  
  101.      * 下午04:54:03  
  102.      */  
  103.     private class UDPThread extends Thread {   
  104.         //服务器每次收发数据的缓冲区,大小是1024个字节   
  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.                     //接收数据包   
  121.                     ds.receive(packet);   
  122.                     System.out.println("地址:"+packet.getAddress()+"  端口:"+packet.getPort()+"数据:"+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.                     //把接收到的数据包发送给所有已连接的客户端   
  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.                         //设置数据包要发送的客户端地址   
  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. }  
[java]  view plain copy
  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.     /**与服务器已经建立链接的客户端数量 */  
  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.      * 接收客户端发送的数据,并把接收到的数据发送给所有客户端,使用UDP协议 
  98.      * @author  
  99.      * zhoujianghai 
  100.      * 2011-5-15 
  101.      * 下午04:54:03 
  102.      */  
  103.     private class UDPThread extends Thread {  
  104.         //服务器每次收发数据的缓冲区,大小是1024个字节  
  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.                     //接收数据包  
  121.                     ds.receive(packet);  
  122.                     System.out.println("地址:"+packet.getAddress()+"  端口:"+packet.getPort()+"数据:"+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.                     //把接收到的数据包发送给所有已连接的客户端  
  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.                         //设置数据包要发送的客户端地址  
  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. }   
[java]  view plain copy
  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发送的数据的问题,server端根据接收到的数据得出发送数据包的客户端的ip地址和端口,不需要进行端口的转发,真机和模拟器一样。代码:

 

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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值