Android:如何检查服务器是否可用?
我正在开发一个连接到服务器的应用程序。至此,如果服务器可用,则登录和数据传输工作正常。当服务器不可用时就会出现问题。在这种情况下,该方法发送登录请求并等待响应。
有谁知道如何检查服务器是否可用(可见)?
必须实现的简单逻辑的伪代码如下:
- String serverAddress = (从配置文件中读取值) //已经完成
- boolean serverAvailable = (检查服务器 serverAddress 是否可用)//必须实现
- (这里来了取决于 serverAvailable 的逻辑)
I am developing an application which connects to the server. By now the login and data transmission works fine if theserver is available. The problem arises when the server is unavailable. In this case the method sends a login request and waits for the response.
Does anyone know how to check if the server is available (visible)?
The pseudocode of the simple logic that has to be implemented is the following:
- String serverAddress = (Read value from configuration file) //already done
- boolean serverAvailable = (Check if the server serverAddress is available)//has to be implemented
- (Here comes the logic which depends on serverAvailable)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
他可能需要 Java 代码,因为他正在开发 Android。 Java 的等价物——我相信它可以在 Android 上运行——应该是:
He probably needs Java code since he's working on Android. The Java equivalent -- which I believe works on Android -- should be:
通过一个简单的类似 ping 的测试,这对我有用:
不要忘记在线程中(而不是在主线程中)运行此函数。
With a simple ping-like test, this worked for me :
Do not forget to run this function in a thread (not in the main thread).
您可以使用
,但当主机未在 tcp 7 上应答时,它无法正常工作。您可以借助此功能检查主机是否在您需要的端口上可用:
you can use
but it doesn't work fine when host is not answering on tcp 7. You can check if the host is available on that port what you need with help of this function:
尝试一下,为我工作,不要忘记激活 android.permission.ACCESS_NETWORK_STATE
try it, work for me and dont forget actived android.permission.ACCESS_NETWORK_STATE
您正在使用 HTTP 吗?然后,您可以在 HTTP 连接上设置超时,如下所示:
如果您随后执行请求,则在给定超时后您将收到异常。
Are you working with HTTP? You could then set a timeout on your HTTP connection, as such:
If you then execute a request, you will get an exception after the given timeout.
哦,不不,Java 中的代码不起作用:InetAddress.getByName("fr.yahoo.com").isReachable(200) 尽管在 LogCat 中我看到了它的 IP 地址(与 20000 毫秒超时相同) 。
看来使用“ping”命令很方便,例如:
Oh, no no, the code in Java doesn't work: InetAddress.getByName("fr.yahoo.com").isReachable(200) although in the LogCat I saw its IP address (the same with 20000 ms of time out).
It seems that the use of the 'ping' command is convenient, for example: