简体   繁体   English

如何检查服务器是否在线?

[英]How to check if a server is online?

I am making some sort of client-server connection. 我正在建立某种客户端-服务器连接。 The client can connect to multiple servers, and therefore needs to know if that server is online. 客户端可以连接到多个服务器,因此需要知道该服务器是否在线。 Instead of first entering all the login information, I want a JLabel to show that the server is online, or not. 我希望首先使用JLabel显示服务器是否在线,而不是首先输入所有登录信息。 How do I check this, without making a real connection to the server? 如何在不与服务器建立真正连接的情况下检查此信息?

The best way is to make a real connection to the server and ask it if it is online, using a method as similar as possible to real use of the server. 最好的方法是建立与服务器的真实连接,并使用与服务器实际使用尽可能相似的方法询问服务器是否在线。 Other methods create independent failure modes and distinct methods that have to be separately maintained and one may fail while the other works. 其他方法会创建独立的故障模式,并且必须分别维护不同的方法,一个方法可能会失败,而其他方法会起作用。

Think about things like proxies and firewalls. 考虑一下代理和防火墙之类的事情。 Why make things difficult for yourself and everyone who has to use your system? 为什么让自己和每个必须使用你的系统的人都很难? Unless there's something very unusual that you haven't told us, there is no good reason to create a totally different access method just to test availability. 除非您没有告诉我们一些非常不寻常的事情,否则没有充分的理由创建一个完全不同的访问方法来测试可用性。

Try something like this to ping it: 尝试这样的东西来ping它:

   InetAddress address = InetAddress.getByName("address");

  if (address.isReachable(3000)) 
      label.setName("online")

I don't know if it is possible to ping the server using java. 我不知道是否可以使用Java ping服务器。 But you can try to ping the ip of the server in the constructor of your Main and if it returns the echo, make the label change its value. 但是您可以尝试在Main的构造函数中ping服务器的ip,如果它返回echo,则使标签更改其值。

Just connect. 只需连接。

The best way to discover whether any resource is usable is to try to use it. 发现任何资源是否可用的最佳方法是尝试使用它。 This applies to network connections, files, anything you like. 这适用于网络连接,文件或任何您喜欢的东西。 Writing secondary tests that exercise other things like isReachable() , exists() , isWritable() , etc., at best just repeat what the system is going to do anyway when you use the resource, and at worst do something different that may yield a different result. 编写执行其他内容的辅助测试,例如isReachable()exists()isWritable()等,最好只重复系统在使用资源时要做的事情,最坏的情况是做一些不同的事情,可能会产生不同的结果。

In either case you are introducing a timing window during which availability may change, in either direction. 在任何一种情况下,您都会引入一个时间窗口,在此期间可用性可能会发生变化。

Use InetAddress.isReachable 使用InetAddress.isReachable

Note that this will check if the server is reachable, not whether a specific URL/service is available. 请注意,这将检查服务器是否可访问,而不是特定的URL /服务是否可用。 For that you'd better make a test request. 为此,您最好提出一个测试请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM