[英]Android Asynctask for socket scan
I am trying to figure out the best way to loop over all ips in a range(IE 192.168.5.0-192.168.5.255) to find devices that are listening on a given port. 我试图找出最好的方法来遍历范围(IE 192.168.5.0-192.168.5.255)中的所有ip,以查找在给定端口上侦听的设备。 The following code is working but I am worried that I wont find all the devices since I have my timeout on my socket too low.
以下代码可以正常工作,但是我担心找不到所有设备,因为我的套接字超时太低了。 The catch 22 is that I want this to be super fast but if I up the timeout it starts to take forever.
陷阱22是我希望这是超快速的,但是如果我超时,它就会永远消失。
private class findNetworkDevices extends AsyncTask<String, Integer, String> {
private String source;
private Activity activity;
private Context context;
public findNetworkDevices(Activity activity) {
this.activity = activity;
context = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
for (int dest = 0; dest < 255; dest++) {
String host = "192.168.5." + dest; // TODO: add net address instead of hardcoding
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(InetAddress.getByName(host), 9999), 50);
Log.v(LOG_TAG, "conn:" + s.toString());
if (s.isConnected()) {
Log.v(LOG_TAG, "connected " + host);
foundDevicesArray.add(host);
} else {
return "failed";
}
} catch (Exception e) {
Log.e(LOG_TAG, "Not found", e);
}
}
Log.v(LOG_TAG, "end");
return "All Done!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListView lv = (ListView) activity.findViewById(R.id.foundDevicesList);
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
}
}
Thanks in advance. 提前致谢。
I went away from using Async because it took so long. 我不使用Async,因为它花了很长时间。 I went with ExecutorService
我去了ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
String ip = getLocalIpAddress();
int endIndex = ip.lastIndexOf(".");
String subnet = ip.substring(0, endIndex);
for (int dest = 0; dest < 255; dest++) {
String host = subnet + "." + dest;
executor.execute(pingRunnable(host));
}
It seems to spawn multiple threads where Async did it in the background but only in one thread. 似乎产生了多个线程,其中Async在后台执行了该操作,但仅在一个线程中执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.