开心六月综合激情婷婷|欧美精品成人动漫二区|国产中文字幕综合色|亚洲人在线成视频

    1. 
      
        <b id="zqfy3"><legend id="zqfy3"><fieldset id="zqfy3"></fieldset></legend></b>
          <ul id="zqfy3"></ul>
          <blockquote id="zqfy3"><strong id="zqfy3"><dfn id="zqfy3"></dfn></strong></blockquote>
          <blockquote id="zqfy3"><legend id="zqfy3"></legend></blockquote>
          打開(kāi)APP
          userphoto
          未登錄

          開(kāi)通VIP,暢享免費(fèi)電子書(shū)等14項(xiàng)超值服

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

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

           

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

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

          服務(wù)器端代碼:

          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.  * 服務(wù)器端  
          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.     /**與服務(wù)器已經(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("一個(gè)新的客戶端已連接,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.         //服務(wù)器每次收發(fā)數(shù)據(jù)的緩沖區(qū),大小是1024個(gè)字節(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è)置數(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.  * 服務(wù)器端 
          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.     /**與服務(wù)器已經(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("一個(gè)新的客戶端已連接,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.         //服務(wù)器每次收發(fā)數(shù)據(jù)的緩沖區(qū),大小是1024個(gè)字節(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è)置數(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“跟服務(wù)器端接收到的不一樣,為了避免了使用UDP通信時(shí),android客戶端接收不到server發(fā)送的數(shù)據(jù)的問(wèn)題,server端根據(jù)接收到的數(shù)據(jù)得出發(fā)送數(shù)據(jù)包的客戶端的ip地址和端口,不需要進(jìn)行端口的轉(zhuǎn)發(fā),真機(jī)和模擬器一樣。代碼:

           

          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
          本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
          打開(kāi)APP,閱讀全文并永久保存 查看更多類似文章
          猜你喜歡
          類似文章
          手機(jī)移動(dòng)平臺(tái)的視頻通訊系統(tǒng)
          類 QQ IM 通訊軟件開(kāi)發(fā)實(shí)戰(zhàn)
          為什么聊天軟件一般采用UDP協(xié)議
          第38講:TCP、UDP網(wǎng)絡(luò)編程
          TCP和UDP數(shù)據(jù)包結(jié)構(gòu)
          TCP狀態(tài)知識(shí)總結(jié)(圖解)
          更多類似文章 >>
          生活服務(wù)
          分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
          綁定賬號(hào)成功
          后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
          如果VIP功能使用有故障,
          可點(diǎn)擊這里聯(lián)系客服!

          聯(lián)系客服