android udp接收
address=InetAddress.getByName(url);
int i=0;
byte[] receiveByte = new byte[1316];
Log.i("2015-6-3","thread running");
dataPacket = new DatagramPacket(receiveByte, receiveByte.length);
if(address==NULL)
{
try {
dataSocket = new DatagramSocket(PORT);
} catch (SocketException e1) {
// TODO Auto-generated catch block
Log.i("2015-6-3","port cannot open");
e1.printStackTrace();
}}else{
try {
dataSocket = new DatagramSocket(PORT,address);
} catch (SocketException e1) {
// TODO Auto-generated catch block
Log.i("2015-6-8","port cannot open");
e1.printStackTrace();
}}
while(true)
{
try {
dataSocket.receive(dataPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("2015-6-3","packet receive failed");
e.printStackTrace();
}
相关代码如上,其中UDP只是监听端口,数据接收没有问题。但是加上IP就直接闪退到上一个activity,求解答。InetAddress.getByName(url)内的url是“239.255.x.x”格式的
----------分割线-------------
经过修改后的代码
swi=1;
try {
dataaddr=new MulticastSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
address = InetAddress.getByName(url);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataaddr.joinGroup(address);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataaddr.receive(dataPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("2015-6-3","packet receive failed");
e.printStackTrace();
}.........
这时出现了一个bug,
W/ContextImpl( 1909): Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1168 com.android.internal.policy.impl.PhoneWindowManager.interceptKeyBeforeQueueing:4109 com.android.server.wm.InputMonitor.interceptKeyBeforeQueueing:357 com.android.server.input.InputManagerService.interceptKeyBeforeQueueing:1352 dalvik.system.NativeStart.run:-2
不知道有没有解,PS:VLC或者ffmpeg都是用c接收这种UDP包的
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以上为解决办法,谢谢@huandu
DatagramSocket(int aPort, InetAddress addr)
这里的addr
只能绑定本机的 IP,你给的 IP 恐怕不是 Android 机器自己的 IP 吧。如果
addr
不是本机 IP,new DatagramSocket(PORT,address)
会抛异常,从而导致dataSocket == null
,后面你在dataSocket.receive
调用时没有捕捉NullPointerException
,所以直接挂掉了。