繁体   English   中英

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

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

我刚刚与本地主机建立了一个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");}
    }}

如果HTTP响应代码超出200-209或无法建立连接,则必须执行以下步骤:

1)如果Jboss服务正在运行,则重新启动。

2)如果Jboss服务未运行,则启动它。

现在,我想知道如何以编程方式知道服务器是否正在运行以执行上述两个步骤..请帮助我..谢谢你

您应该捕获在超时(服务器根本不运行)发生时上升的IOException。

像这样的东西:

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");}
    }}

我认为这已经讨论过了。 你需要捕获异常。 你可能想看看像这样

暂无
暂无

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

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