我注意到我的设备上没有收到任何多播数据包.
这是服务器的代码(在PC上运行):
public class MulticastServer{private int port;private boolean running = false;private MulticastSocket serverSocket;private InetAddress group;private String multicastAddress = "230.192.0.11";public MulticastServer(int port) { super(); this.port = port; init();}public MusicStreamerServer() { this(5500);}private voID init() { try { group = InetAddress.getByname(multicastAddress); serverSocket = new MulticastSocket(port); serverSocket.joinGroup(group); } catch (IOException e) { e.printstacktrace(); }}public voID start() throws IOException { System.out.println("server started"); if (running) return; running = true; new Thread(new Runnable() { @OverrIDe public voID run() { byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf,buf.length,group,port); String msg = "msg"; while (running) { packet.setData(msg.getBytes(),msg.length()); try { serverSocket.send(packet); } catch (IOException e) { e.printstacktrace(); } } } }).start();}public voID stop() throws IOException { running = false;} }
这是androID客户端的代码:
public class MainActivity extends Activity {private MulticastSocket socket;private InetAddress group;private String multicastAddress = "230.192.0.11";private int port = 5500;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); init();}private voID init() { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); try { group = InetAddress.getByname(multicastAddress); socket = new MulticastSocket(port); socket.joinGroup(group); socket.setbroadcast(true); } catch (IOException e) { e.printstacktrace(); Log.wtf("init",e.getMessage()); } new Thread(new Runnable() { @OverrIDe public voID run() { WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock multicastLock = wm .createMulticastLock("mylock"); multicastLock.acquire(); byte[] buf = new byte[1024]; while (true) { try { socket.receive(packet); Log.d("receiver","received = " + (new String(packet.getData()))); } catch (IOException e) { e.printstacktrace(); } } } }).start();}@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main,menu); return true;}}
我用2种不同的设备测试了代码. Nexus4和Nexus7(2013)都运行最新的AndroID.
有人能帮助我吗?
谢谢
解决方法 我已经看到这个问题真的不一致了.AndroID版本:4.2.x
在三星S4活跃:
多播正在按预期工作.
在Samsung Note 10.1和Nexus 4.2.3上
多播未按预期工作.
不支持239.x.x.x(遗憾的是它是用于多播电视的…)
224.0.0.251正在按预期工作.
我认为他们有面具的错误.
通常是组播地址
| 1 1 1 0 | MulTICAST地址| 224.0.0.0 – 239.255.255.255
11100000.00000000.00000000.00000001 = 224.0.0.1 11101111.00000000.00000000.00000001 = 239.0.0.1
所以掩码应该是224.0.0.0/4而不是224.0.0.0/8
@H_404_2@ 总结以上是内存溢出为你收集整理的Android无法接收组播数据包全部内容,希望文章能够帮你解决Android无法接收组播数据包所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)