Android 之简单UDP通信

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 之简单UDP通信相关的知识,希望对你有一定的参考价值。

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;//声明socket
19     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            @Override
28            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()//关闭Socket
86     {
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             @Override
20             public void onClick(View view) {
21 
22             }
23         });
24 
25         Mode2Button.setOnClickListener(new View.OnClickListener() {
26             @Override
27             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             @Override
37             public void onClick(View view) {
38                 new Thread(new Runnable() {
39                     @Override
40                     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             @Override
52             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通信的主要内容,如果未能解决你的问题,请参考以下文章

UDP通信简单 小结

一起Talk Android吧(第三百二十八回:Android中网络通信之UPD概述)

一起Talk Android吧(第三百二十九回:Android中网络通信之UPD Socket)

java 网络编程之UDP通信和简单的群聊程序

android udp通信(应用层与底层硬件的通信)

Python中的端口协议之基于UDP协议的通信传输