为什么我不能通过互联网访问我的Web服务器?

时间:2018-09-04 19:41:45

标签: java http webserver

我想在我的lightail实例上运行这个简单的Java Web服务器。

    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class Server {
        private static final Logger LOGGER = Logger.getLogger(Logger.class.getName());

        public static void main(String[] args) {
            final int PORT = 8000;
            new Server(PORT);
        }

        private Server(int port) {
            HttpServer server = null;
            try {
                server = HttpServer.create(new InetSocketAddress(port), 0);
                LOGGER.log(Level.INFO, "Server has been started!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            server.createContext("/request", new MyHttpHandler() {
                @Override
                public void handle(com.sun.net.httpserver.HttpExchange httpExchange) throws IOException {
                    super.handle(httpExchange);
                    String response = "This is the response";
                    httpExchange.sendResponseHeaders(200, response.length());
                    OutputStream outputStream = httpExchange.getResponseBody();
                    outputStream.write(response.getBytes());
                    LOGGER.log(Level.INFO, "response: " + response);
                    outputStream.close();
                }
            });
            server.setExecutor(null);
            server.start();
         }

        private class MyHttpHandler implements HttpHandler {
            @Override
            public void handle(com.sun.net.httpserver.HttpExchange httpExchange) throws IOException {
                LOGGER.log(Level.INFO, "request: " + httpExchange.getRequestURI());
            }
    }
}

它可以正常工作,但不能响应来自Internet的请求吗?
那可能是什么?我通过sudo ufw allow 8000打开了端口,但是什么都没有改变。

0 个答案:

没有答案