我正在编写代码以从我的移动设备发送UDP Multicast
过来。Wifi
网络中的其他设备上运行着一个服务器代码。服务器将侦听多播并使用其 IP 地址和系统类型(类型:计算机、移动设备、Raspberry Pi、Flyports 等)进行响应
在已发送 的移动设备上UDP Multicast
,我需要获取响应的设备列表UDP Multicast
。
为此,我创建了一个类,它将作为device details
.
DeviceDetails.class
public class DeviceDetails
{
String DeviceType;
String IPAddr;
public DeviceDetails(String type, String IP)
{
this.DeviceType=type;
this.IPAddr=IP;
}
}
我在group address of 225.4.5.6
和发送 UDP 多播数据包Port Number 5432
。
我已经创建了一个类,它将调用一个thread
将发送UDP Packets
. 另一方面,我制作了一个receiver thread
实现Callable Interface 以返回响应的设备列表。
这是代码:
MulticastReceiver.java
public class MulticastReceiver implements Callable<DeviceDetails>
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
boolean check = true;
public MulticastReceiver()
{
try
{
socket = new DatagramSocket(5500);
}
catch(Exception ioe)
{
System.out.println(ioe);
}
}
@Override
public DeviceDetails call() throws Exception
{
// TODO Auto-generated method stub
try
{
byte[] inBuf = new byte[WifiConstants.DGRAM_LEN];
//System.out.println("Listening");
inPacket = new DatagramPacket(inBuf, inBuf.length);
if(check)
{
socket.receive(inPacket);
}
String msg = new String(inBuf, 0, inPacket.getLength());
Log.v("Received: ","From :" + inPacket.getAddress() + " Msg : " + msg);
DeviceDetails device = getDeviceFromString(msg);
Thread.sleep(100);
return device;
}
catch(Exception e)
{
Log.v("Receiving Error: ",e.toString());
return null;
}
}
public DeviceDetails getDeviceFromString(String str)
{
String type;
String IP;
type=str.substring(0,str.indexOf('`'));
str = str.substring(str.indexOf('`')+1);
IP=str;
DeviceDetails device = new DeviceDetails(type,IP);
return device;
}
}
以下代码是调用的活动Receiver Thread
:
public class DeviceManagerWindow extends Activity
{
public void searchDevice(View view)
{
sendMulticast = new Thread(new MultiCastThread());
sendMulticast.start();
ExecutorService executorService = Executors.newFixedThreadPool(1);
List<Future<DeviceDetails>> deviceList = new ArrayList<Future<DeviceDetails>>();
Callable<DeviceDetails> device = new MulticastReceiver();
Future<DeviceDetails> submit = executorService.submit(device);
deviceList.add(submit);
DeviceDetails[] devices = new DeviceDetails[deviceList.size()];
int i=0;
for(Future<DeviceDetails> future :deviceList)
{
try
{
devices[i] = future.get();
}
catch(Exception e)
{
Log.v("future Exception: ",e.toString());
}
}
}
}
receive method
现在接收数据包的标准方法是在无限循环下调用。但我只想在前 30 秒内接收传入连接,然后停止寻找连接。
This is similar to that of a bluetooth searching. It stops after 1 minute of search.
现在问题在于,我可以使用计数器,但问题 thread.stop
现在已经被贬低了。不仅如此,如果我将 receive method
无限循环置于无限循环之下,它将永远不会返回该值。
我应该怎么办。?我想搜索 30 秒,然后停止搜索并希望返回响应设备的列表。