安卓开发博客

Android 使用udp发送广播

2018-07-19  本文已影响2人  梦醒了i77

最近做项目时,遇到一个对新人我来说稍微有点麻烦的事情!

那就是使用udp协议发送广播获取服务器地址!

http都好说,github开源项目不知道有多少。

可是再难的问题也要去解决!

发送广播需要权限!

AndroidManifest.xml 中添加:

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

最少这三个是必须的,多的也忘了!
原因后面会讲到

使用到RxJava:

implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.2'

udp发送与接受都需指定端口号
广播地址是255.255.255.255

 private static final int SEND_BROADCAST_PORT = "发送端口";
 private static final int RECV_BROADCAST_PORT = “接收端口”;
 private static final String BROADCAST_ADDR = "255.255.255.255";
 private static final String TAG = "UdpService";
 public Boolean IsThreadDisable = false;//指示监听线程是否终止

在之前添加权限的时候CHANGE_WIFI_MULTICAST_STATE有添加这个
往下面看

  WifiManager.MulticastLock lock;
  WifiManager manager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  lock = manager.createMulticastLock("udpservice");

接下来我们开启接收udp信息

  private void receiveInit() {
        LogUtil.d(TAG, "receiveInit");
        byte[] message = new byte[128];

        try {
            final DatagramSocket datagramSocket = new DatagramSocket(RECV_BROADCAST_PORT);
            final DatagramPacket datagramPacket = new DatagramPacket(message, message.length);
            Flowable.just("")
                    .observeOn(Schedulers.newThread())
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(Object o) throws Exception {
                            startListener(datagramSocket, datagramPacket);
                        }
                    });
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    private void startListener(DatagramSocket datagramSocket, DatagramPacket datagramPacket) {
        while (!IsThreadDisable) {
            LogUtil.d(TAG, "开始监听");
            try {
                lock.acquire();
                datagramSocket.receive(datagramPacket);
                String ip = datagramPacket.getAddress()
                        .getHostAddress().toString();
                EventBus.getDefault().post(ip);
                this.lock.release();
                IsThreadDisable = true;
                stopSelf();
            } catch (Exception e) {
                LogUtil.d(TAG, e.toString());
            }finally {
                if (datagramSocket != null) {
                    datagramSocket.close();
                }
            }
        }
    }

发送消息?

 private void beforeSend() {
        Flowable.just("")
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        sendMessage();
                    }
                });
    }


  private void sendMessage() {
        String message = "hello! i is android client";
        DatagramSocket datagramSocket = null;
        try {

            LogUtil.d(TAG, "准备发送:" + message);
            datagramSocket = new DatagramSocket();
            datagramSocket.setBroadcast(true);
            InetAddress address = InetAddress.getByName(BROADCAST_ADDR);
            DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.length(),     address, SEND_BROADCAST_PORT);
            datagramSocket.send(datagramPacket);
        } catch (Exception e) {
             LogUtil.d(TAG,e.toString());
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
    }

谢谢该作者的文章让我学会udp发送
https://blog.csdn.net/tanghongchang123/article/details/53609237

上一篇下一篇

猜你喜欢

热点阅读