猿问

android udp接收

address=InetAddress.getByName(url);
inti=0;
byte[]receiveByte=newbyte[1316];
Log.i("2015-6-3","threadrunning");
dataPacket=newDatagramPacket(receiveByte,receiveByte.length);
if(address==NULL)
{
try{
dataSocket=newDatagramSocket(PORT);
}catch(SocketExceptione1){
//TODOAuto-generatedcatchblock
Log.i("2015-6-3","portcannotopen");
e1.printStackTrace();
}}else{
try{
dataSocket=newDatagramSocket(PORT,address);
}catch(SocketExceptione1){
//TODOAuto-generatedcatchblock
Log.i("2015-6-8","portcannotopen");
e1.printStackTrace();
}}
while(true)
{
try{
dataSocket.receive(dataPacket);
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
Log.i("2015-6-3","packetreceivefailed");
e.printStackTrace();
}
相关代码如上,其中UDP只是监听端口,数据接收没有问题。但是加上IP就直接闪退到上一个activity,求解答。InetAddress.getByName(url)内的url是“239.255.x.x”格式的
----------分割线-------------
经过修改后的代码
swi=1;
try{
dataaddr=newMulticastSocket(port);
}catch(IOExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}
try{
address=InetAddress.getByName(url);
}catch(UnknownHostExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
try{
dataaddr.joinGroup(address);
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
try{
dataaddr.receive(dataPacket);
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
Log.i("2015-6-3","packetreceivefailed");
e.printStackTrace();
}.........
这时出现了一个bug,
W/ContextImpl(1909):Callingamethodinthesystemprocesswithoutaqualifieduser:android.app.ContextImpl.sendBroadcast:1168com.android.internal.policy.impl.PhoneWindowManager.interceptKeyBeforeQueueing:4109com.android.server.wm.InputMonitor.interceptKeyBeforeQueueing:357com.android.server.input.InputManagerService.interceptKeyBeforeQueueing:1352dalvik.system.NativeStart.run:-2
不知道有没有解,PS:VLC或者ffmpeg都是用c接收这种UDP包的
蓝山帝景
浏览 443回答 2
2回答

万千封印

MulticastSocketdataaddr=newMulticastSocket(1234);InetAddressaddress=InetAddress.getByName("239.0.0.1");dataaddr.joinGroup(address);byte[]receiveByte=newbyte[1316];dataPacket=newDatagramPacket(receiveByte,receiveByte.length);try{dataaddr.receive(dataPacket);}catch(IOExceptione){//TODOAuto-generatedcatchblockLog.i("2015-6-3","packetreceivefailed");e.printStackTrace();}以上为解决办法

ITMISS

DatagramSocket(intaPort,InetAddressaddr)这里的addr只能绑定本机的IP,你给的IP恐怕不是Android机器自己的IP吧。如果addr不是本机IP,newDatagramSocket(PORT,address)会抛异常,从而导致dataSocket==null,后面你在dataSocket.receive调用时没有捕捉NullPointerException,所以直接挂掉了。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答