我试图找出在一个范围内(IE 192.168.5.0-192.168.5.255)循环所有 ips 以找到正在侦听给定端口的设备的最佳方法。以下代码正在运行,但我担心我找不到所有设备,因为我的套接字上的超时太低了。第 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();
}
}
提前致谢。