我正在broadcast message
从我的 android 手机向网络中的设备发送一个消息,并等待他们回复。
网络中有n
许多设备。
现在我需要创建发送回复的设备列表。
我正在使用Runnable接口并接收回复数据包。
如何准备设备列表?
因为线程不会返回任何值。我想准备一个随机列表。类似于蓝牙搜索。
我尝试使用synchronized
方法
public static synchronized void addDevice(DeviceDetails device) throws IOException
{
listIsChanged=true; //if the list changes that means if there is a device then this method will be called.
deviceList = device;
Log.v("device added with IP:",device.getDeviceIP());
}
MulticastReceiver.java
public class MulticastReceiver implements Runnable
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
byte[] inBuf;
public MulticastReceiver()
{
try
{
socket = new DatagramSocket(WifiConstants.PORT_NO_RECV);
inBuf = new byte[WifiConstants.DGRAM_LEN];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.setSoTimeout(2*60*1000);
}
catch(Exception ioe)
{
System.out.println(ioe);
}
}
@Override
public void run()
{
//System.out.println("Listening");
try
{
for(long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(2); stop>System.nanoTime();)
{
Log.v("yoyo","yoyo honey singh");
socket.receive(inPacket);
Log.v("checking to receive","received");
String msg = new String(inBuf, 0, inPacket.getLength());
Log.v("Received: ","From :" + inPacket.getAddress() + " Msg : " + msg);
DeviceDetails device = getDeviceFromString(msg);
DeviceManagerWindow.addDevice(device);
Thread.sleep(1000);
}
}
/**try
{
socket.setSoTimeout(5000);
socket.receive(inPacket);
Log.v("checking to receive","received");
String msg = new String(inBuf, 0, inPacket.getLength());
Log.v("Received: ","From :" + inPacket.getAddress() + " Msg : " + msg);
DeviceDetails device = getDeviceFromString(msg);
DeviceManagerWindow.addDevice(device);
Thread.sleep(1000);
}**/
catch(Exception e)
{
Log.v("Receiving Error: ",e.toString()+" No Packets Received");
}
finally
{
socket.close();
}
}
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;
}
}
DeviceDetails.java
package com.example.devicecontrolpanel;
public class DeviceDetails
{
private String DeviceType;
private String IPAddr;
public DeviceDetails(String type, String IP)
{
this.DeviceType=type;
this.IPAddr=IP;
}
public String getDeviceType()
{
return this.DeviceType;
}
public String getDeviceIP()
{
return this.IPAddr;
}
}