Android 之簡單UDP通訊

來源:互聯網
上載者:User

標籤:

一 Android UDP通訊編程步驟

     伺服器端: 1.建立Socket

                        2.監聽連接埠

        3.接收資料

        4.實現資料發送

    用戶端:直接實現資料發送即可

 

二 代碼,實現一個簡單的UdpHelper類

 1 package com.br.delphi.centercontrol; 2  3 import android.os.Handler; 4 import android.os.Message; 5 import android.util.Log; 6  7 import java.io.IOException; 8 import java.net.DatagramPacket; 9 import java.net.DatagramSocket;10 import java.net.InetAddress;11 import java.net.SocketException;12 import java.net.UnknownHostException;13 14 /**15  * Created by delphi on 16-6-11.16  */17 public class UdpHelper {18     private DatagramSocket socket;//聲明socket19     private DatagramPacket packet;20     private Handler handler;//將收到的資訊通過handl傳送到需要使用的地方21 22     private  Thread ServerThread;23     public UdpHelper(final Handler handler)24     {25        this.handler=handler;26        ServerThread=new Thread(new Runnable() {//udp接收資料線程27            @Override28            public void run() {29                while (true) {30                    byte[] receiveBytes = new byte[1024];31                    packet = new DatagramPacket(receiveBytes, receiveBytes.length);32                    try {33                        socket.receive(packet);34                        InetAddress client = packet.getAddress();35                        String clientIP = client.getHostAddress();//擷取用戶端的IP地址36                        byte[] receiveData = packet.getData();//擷取發送的資料37                        String dataStr =new String(receiveData);38                        Log.d("udp",clientIP);39                        Log.d("udp",dataStr);40 41                        Message msg = new Message();//通過Message 傳送資料42                        msg.what = 0;43                        msg.obj = dataStr;44                        handler.sendMessage(msg);45                    } catch (IOException e) {46                        e.printStackTrace();47                    }48                }49 50            }51        });52 53     }54     public  void Listen(int port)//初始化監聽連接埠55     {56         try {57             socket=new DatagramSocket(port);58             ServerThread.start();59         } catch (SocketException e) {60             e.printStackTrace();61         } catch (IOException e) {62             e.printStackTrace();63         }64     }65 66     public  void  SendData(byte[] data,String Ip,int port){//發送資料67         try {68             packet=new DatagramPacket(data,data.length,InetAddress.getByName(Ip),port);69             if(socket==null)70                 socket=new DatagramSocket();71             socket.send(packet);72         } catch (UnknownHostException e) {73             e.printStackTrace();74         } catch (IOException e) {75             e.printStackTrace();76         }77 78     }79 80     public  void SendData(String data,String Ip,int port)//發送字元資料,注意發送的編碼格式81     {82         byte[] tmp=data.getBytes();83         SendData(tmp,Ip,port);84     }85     public  void  Close()//關閉Socket86     {87         if(socket!=null)88             socket.close();89     }90 }


三 簡單使用

 1  private  static Handler handler; 2     private  UdpHelper Udp; 3  4     @Override 5     protected void onCreate(Bundle savedInstanceState) { 6         super.onCreate(savedInstanceState); 7         setContentView(R.layout.activity_main); 8  9 10 11         Button Mode1Button=(Button) findViewById(R.id.button);12         Button Mode2Button=(Button) findViewById(R.id.button2);13         Button Mode3Button=(Button) findViewById(R.id.button3);14 15         final EditText editText= (EditText) findViewById(R.id.editText);16         final TextView textView= (TextView) findViewById(R.id.textView2);17 18         Mode1Button.setOnClickListener(new View.OnClickListener() {19             @Override20             public void onClick(View view) {21 22             }23         });24 25         Mode2Button.setOnClickListener(new View.OnClickListener() {26             @Override27             public void onClick(View view) {28 29 30                // Toast toast=Toast.makeText(this,"Hello",);31                 textView.setText("Hello,world");32             }33         });34 35         Mode3Button.setOnClickListener(new View.OnClickListener() {36             @Override37             public void onClick(View view) {38                 new Thread(new Runnable() {39                     @Override40                     public void run() {41                         String str="hello";42                         byte[] data=str.getBytes();43                         Udp.SendData(data,"192.168.0.107",9000);44                     }45                 }).start();46 47             }48         });49 50         handler=new Handler(){51             @Override52             public void handleMessage(Message msg)53             {54                 if (msg.what==0)55                 {56                     textView.setText((String)msg.obj);57                 }58             }59 60         };61         Udp=new UdpHelper(handler);62         Udp.Listen(8000);63 64     }


 



 

Android 之簡單UDP通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.