今日长缨在手,何时缚住苍龙。这篇文章主要讲述Android对UDP组播接收数据的有限支持相关的知识,希望能为你提供帮助。
最近,想做一个跨平台的局域网的文件传输软件,思路是组播设备信息,TCP连接传输文件。于是进行了一次简单的UDP组播测试,发现android对于UDP组播接收数据的支持即极为有限。
部分代码如下
文章图片
文章图片
1 package com.hsocket.Udp; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 7 public class UdpReceiver { 8protected DatagramSocket client=null; 9private OnReceiveListener mOnReceiveListener=null; 10private Thread thrRecv=null; 11protected int port=0; 12public UdpReceiver(int port){ 13this.port=port; 14} 15protected DatagramSocket Create() throws IOException{ 16return new DatagramSocket(this.port); 17} 18public void addOnReceiveListener(OnReceiveListener mOnReceiveListener){ 19this.mOnReceiveListener=mOnReceiveListener; 20} 21public void Stop(){ 22if(this.thrRecv!=null) this.thrRecv.interrupt(); 23this.Close(); 24} 25public void Listen() throws IOException{ 26this.Close(); 27this.client=this.Create(); 28if(this.thrRecv!=null) this.thrRecv.interrupt(); 29this.thrRecv=new Thread(new Runnable() { 30@Override 31public void run() { 32while(!Thread.interrupted()){ 33ReceiveEventArgs args=new ReceiveEventArgs(); 34try { 35DatagramPacket packet=UdpReceiver.this.Receive(); 36args.Address=packet.getAddress(); 37args.Result=packet.getData(); 38args.Length=packet.getLength(); 39args.Error=false; 40} catch (IOException e) { 41e.printStackTrace(); 42args.Exception=e; 43args.Error=true; 44} 45UdpReceiver.this.OnReceive(args); 46if(UdpReceiver.this.mOnReceiveListener!=null) 47UdpReceiver.this.mOnReceiveListener.OnReceive(UdpReceiver.this, args); 48} 49} 50}); 51this.thrRecv.start(); 52} 53protected DatagramPacket Receive() throws IOException{ 54byte[] recvBuf = new byte[4096]; 55DatagramPacket recvPacket= new DatagramPacket(recvBuf , recvBuf.length); 56this.client.receive(recvPacket); 57return recvPacket; 58} 59protected void Close(){ 60if(this.client!=null) this.client.close(); 61} 62protected void OnReceive(ReceiveEventArgs args){ 63 64} 65 }
View Code
文章图片
文章图片
1 package com.hsocket.Udp; 2 3 import java.io.IOException; 4 import java.net.DatagramSocket; 5 import java.net.InetAddress; 6 import java.net.MulticastSocket; 7 8 public class UdpMultcastReceiver extends UdpReceiver { 9 10private InetAddress multicastAddr=null; 11public UdpMultcastReceiver(InetAddress multicastAddr,int port) { 12super(port); 13this.multicastAddr=multicastAddr; 14} 15 16@Override 17protected DatagramSocket Create() throws IOException { 18MulticastSocket socket=new MulticastSocket(this.port); 19socket.joinGroup(this.multicastAddr); 20socket.setLoopbackMode(false); 21return socket; 22} 23 }
View Code【Android对UDP组播接收数据的有限支持】发现UDP组播接收数据在部分机型存在文件,与系统有极大关系。小米、华为的手机的深度定制系统对UDP的封杀极为严重,折腾开始了
推荐阅读
- Vue 2.0 Application Sample
- android 编译调用C代码
- app 设计原则 ,步骤
- android实现gif图与文字混排
- android SQLite 批量插入数据慢的解决方案 (针对于不同的android api 版本)
- 必须尝试的10种最佳Discord音板合集
- Mac的11款最佳文件粉碎机软件合集
- Android和iPhone的5大密码生成器应用程序合集
- Windows和Mac的13款最佳免费流程图软件合集