[英]Connection to server times out android
I am trying to check if server is online in android. 我正在尝试检查服务器是否在android中处于联机状态。 I have following code on a button onclick listener block:
我在按钮onclick监听器块上有以下代码:
boolean exists = false;
try {
SocketAddress sockaddr = new InetSocketAddress("google.com", 80);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
exists = true;
}catch(Exception e){
}
if ( exists == true) {
Toast.makeText(getApplicationContext(), "Host is reachable!!! =)",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Host is NOT reachable!!! =(",
Toast.LENGTH_LONG).show();
}
Thing is that, whatever host or ip i check, its always offline. 事情是,无论我检查的主机或IP,它总是脱机。
What could be the problem? 可能是什么问题呢?
I have this permission in androidmanifest: 我在androidmanifest中有这个权限:
<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Try this 尝试这个
InetAddress.getByName(host).isReachable(timeOut)
or 要么
boolean exists = false;
try {
SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
exists = true;
}catch(Exception e){
}
I prefer to use HttpClient. 我更喜欢使用HttpClient。 Something like:
就像是:
getURL = "http://www.msftncsi.com/ncsi.txt"
HttpGet getHttp = new HttpGet(getURL);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse responseGet = client.execute(getHttp);
HttpEntity resEntityGet = responseGet.getEntity();
If HttpEntity returns null then I assume there is no connectivity. 如果HttpEntity返回null,那么我假设没有连接。
You must surround with try catch and assume there is no connectivity when enter in the catch 您必须使用try catch进行环绕,并假设在进入catch时没有连接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.