Android Socket通信--UdpClient

作者: hadisi5216 | 来源:发表于2016-07-29 12:15 被阅读1174次
    这只是一张图片

    本文原创,欢迎随便匿名转载,你高兴就行。

    上次写了一篇Android Socket通信--TcpClient,最近项目中又用到了udp通信的东西,于是写了这个UdpClientConnecter,希望有要用的哥们直接伸手吧。


    UdpClientConnecter

    package com.hadisi.socket;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    /**
     * Created by hadisi on 2016/7/22.
     */
    
    public class UdpClientConnector {
        private static UdpClientConnector mUdpClientConnector;
        private ConnectLinstener mListener;
        private Thread mSendThread;
    
        private byte receiveData[] = new byte[1024];
        private String mSendHexString;
    
        private boolean isSend = false;
    
        public interface ConnectLinstener {
            void onReceiveData(String data);
        }
    
        public void setOnConnectLinstener(ConnectLinstener linstener) {
            this.mListener = linstener;
        }
    
        public static UdpClientConnector getInstance() {
            if (mUdpClientConnector == null) {
                mUdpClientConnector = new UdpClientConnector();
            }
            return mUdpClientConnector;
        }
    
        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1000:
                        if (mListener != null) {
                            mListener.onReceiveData(msg.getData().getString("data"));
                        }
                        break;
                }
            }
        };
    
        /**
         * 创建udp发送连接(服务端ip地址、端口号、超时时间)
         *
         * @param ip
         * @param port
         * @param timeOut
         */
        public void createConnector(final String ip, final int port, final int timeOut) {
            if (mSendThread == null) {
                mSendThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            if (!isSend)
                                continue;
                            DatagramSocket socket = null;
                            try {
                                socket = new DatagramSocket();
                                socket.setSoTimeout(timeOut);
                                InetAddress serverAddress = InetAddress.getByName(ip);
                                byte data[] = mSendHexString.getBytes("utf-8");
                                DatagramPacket sendPacket = new DatagramPacket(data, data.length, serverAddress, port);
                                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                                socket.send(sendPacket);
                                socket.receive(receivePacket);
                                Message msg = new Message();
                                msg.what = 1000;
                                Bundle bundle = new Bundle();
                                bundle.putString("data", new String(receivePacket.getData()));
                                msg.setData(bundle);
                                mHandler.sendMessage(msg);
                                socket.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            isSend = false;
                        }
                    }
                });
                mSendThread.start();
            }
        }
    
        /**
         * 发送数据
         *
         * @param str
         */
        public void sendStr(final String str) {
            mSendHexString = str;
            isSend = true;
        }
    }
    

    怎么用它?

    • 获取UdpClientConnector单利对象
    udpClientConnector = UdpClientConnector.getInstance();
    
    • 创建udp发送连接(服务端ip地址、端口号、超时时间);用udp广播通信ip为"255.255.255.255"
    udpClientConnector.createConnector("服务端ip地址",服务器端端口号,超时时间);
    
    • 实现接收数据接口OnConnectLinstener,onReceiveData(String data)中的data就是服务端返回的数据;
    udpClientConnector.setOnConnectLinstener(new UdpClientConnector.ConnectLinstener() {
        @Override
        public void onReceiveData(String data) {
            //do somethings
        }
    });
    

    相关文章

      网友评论

      • _ChTj:DatagramSocket receiver卡住?

      本文标题:Android Socket通信--UdpClient

      本文链接:https://www.haomeiwen.com/subject/nplzjttx.html