简体   繁体   中英

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. 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:

   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. 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.

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.

In either case you are introducing a timing window during which availability may change, in either direction.

Use InetAddress.isReachable

Note that this will check if the server is reachable, not whether a specific URL/service is available. For that you'd better make a test request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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