我有一个OpenPicus Flypport
设备,当通过端口号50000( UDP )查询正确的字符串时,会发送JSON
字符串。
那不仅仅是信息的强制性
我正在做的是用适当的json查询设备,然后设备回复。但我的Android代码没有收到回复。我已经完成了所有必需的WIFIManager Code
和Wifi Permissions
。
为了检查Android是否正在播放天气,我写了一个在我的笔记本电脑上运行的java程序。在那里,我发现Android和Flyport设备都在进行通信。
我写了以下代码:
从ANDROID发送
System.out.println("Sending Flyport");
FlyportDriver flyDriver = new FlyportDriver();
sendMulticastFlyport = new Thread(new FlyportSender(set.getFlyportIP() , flyDriver.getDeviceDiscovery()));
//flyport.getDeviceDiscovery is JSON String. Sending is fine. No problem
sendMulticastFlyport.start();
System.out.println("Flyport Send: "+flyDriver.getDeviceDiscovery());
deviceStartCounter++;
接收ANDROID
private class DeviceSearcher extends AsyncTask<Void, DeviceInformation ,Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
//TableLayout deviceTable = (TableLayout) findViewById(951357);
TableRow tr = new TableRow(getApplicationContext());
LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(layout);
TextView tv = new TextView(getApplicationContext());
tv.setText("Searching...");
tv.setLayoutParams(layoutParam);
tv.setTextColor(Color.WHITE);
tv.setVisibility(View.VISIBLE);
tr.addView(tv);
deviceTable.addView(tr);
}
@Override
protected Void doInBackground(Void... arg0)
{
new Thread()
{
public void run()
{
MulticastSocket socketFlyport=null;
try
{
socketFlyport = new MulticastSocket(50000);
socketFlyport.setSoTimeout(1*20*1000);
byte[] inBufFlyport = new byte[1024];
DatagramPacket inPacketFlyport = new DatagramPacket(inBufFlyport, inBufFlyport.length);
while(true)
{
System.out.println("Listening..."); //Printing
socketFlyport.receive(inPacketFlyport); //not receiving
String msg = new String(inBufFlyport, 0, inPacketFlyport.getLength());
Log.v("Received:","Received Flyport From :" + inPacketFlyport.getAddress() + " Msg : " + msg);
String IP = inPacketFlyport.getAddress().toString();
System.out.println(Utils.getIPAddress(true));
try
{
System.out.println("Received");
DeviceInformation device = new DeviceInformation(3, IP.substring(1), msg, getApplicationContext());
publishProgress(device);
}
catch(Exception e)
{
System.out.println(e.toString());
}
Log.v("Received:","Received Flyport From :" + inPacketFlyport.getAddress() + " Msg : " + msg);
System.out.println();
Thread.sleep(2500);
}
}
catch(Exception e)
{
Log.v("Exception:","During Receiving Flyport: "+e.toString());
publishProgress((DeviceInformation)null);
}
finally
{
socketFlyport.close();
}
}
}.start();
return null;
}
如果您将看到我已经打印了一些变量。
答案 0 :(得分:1)
是的,正如EJP所说,如果您正在使用多播,那么您需要加入多播组。为了清楚起见,您应该展示您对MulticastLock的使用以及您所请求的Android权限。
话虽如此,似乎Android中的多播支持并不像某些使用可能希望的那样坚固。见http://codeisland.org/2012/udp-multicast-on-android/
我最初认为它是否真的有用,或者可能取决于设备。它不适用于我的Nexus5。见https://code.google.com/p/android/issues/detail?id=51195
但后来我发现重置我的路由器使Android设备开始接收多播帖子。我怀疑Android设备经常出现这种情况。