Nik*_*lin 36 networking android connectivity
我正在开发一个连接到服务器的应用程序.到目前为止,如果服务器可用,登录和数据传输工作正常.服务器不可用时会出现问题.在这种情况下,该方法发送登录请求并等待响应.
有谁知道如何检查服务器是否可用(可见)?
必须实现的简单逻辑的伪代码如下:
Sea*_*wen 49
他可能需要Java代码,因为他在Android上工作.Java相当 - 我相信在Android上运行 - 应该是:
InetAddress.getByName(host).isReachable(timeOut)
Run Code Online (Sandbox Code Playgroud)
Gau*_*lio 19
通过简单的类似ping的测试,这对我有用:
static public boolean isURLReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://192.168.1.13"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在线程中运行此函数(不在主线程中).
小智 5
您可以使用
InetAddress.getByName(host).isReachable(timeOut)
Run Code Online (Sandbox Code Playgroud)
但是当主机没有在tcp 7上应答时,它无法正常工作.您可以通过此功能检查主机在该端口上是否可用所需的内容:
public static boolean isHostReachable(String serverAddress, int serverTCPport, int timeoutMS){
boolean connected = false;
Socket socket;
try {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(serverAddress, serverTCPport);
socket.connect(socketAddress, timeoutMS);
if (socket.isConnected()) {
connected = true;
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
socket = null;
}
return connected;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73583 次 |
| 最近记录: |