简体   繁体   English

如何以编程方式知道服务器是否正在运行?

[英]How can programmatically know whether Server is running or not?

I just made a url connection to local host:8080 and checked the http response code between 200-209 using JBOSS server. 我刚刚与本地主机建立了一个url连接:8080并使用JBOSS服务器检查了200-209之间的http响应代码。

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}

If HTTP Response code outside of 200-209 or unable to make connection, then it has to perform the following steps: 如果HTTP响应代码超出200-209或无法建立连接,则必须执行以下步骤:

1)If Jboss Service is running, then restart. 1)如果Jboss服务正在运行,则重新启动。

2)If Jboss Service is not running, then start it. 2)如果Jboss服务未运行,则启动它。

Now here I want to know how can programmatically know whether Server is running or not in order to perform above 2 steps.. Please help me..Thanks you 现在,我想知道如何以编程方式知道服务器是否正在运行以执行上述两个步骤..请帮助我..谢谢你

You should catch the IOException that rise when a timeout (server not running at all) occurs. 您应该捕获在超时(服务器根本不运行)发生时上升的IOException。

Something like this: 像这样的东西:

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");

try {
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
} catch (IOException ex) {
    // (probably) service is not running 
    // start service
    return;
}

connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}

I think this is something already discussed. 我认为这已经讨论过了。 You need to catch exception for that. 你需要捕获异常。 You may want to look into something like this 你可能想看看像这样

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

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