主类:
Main {
public static void main(String[] args) {
final HTTPServer server = new HTTPServer(9999);
server.start();
System.out.println("Server started!");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
server.stop();
System.out.println("Server stopped!");
}));
}
}
HTTPServer {
// for debug
private static int threadNumber;
private final int port;
private Thread listenThread;
public HTTPServer(int port) {
this.port = port;
}
void start() {
listenThread = new Thread() {
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
while (!interrupted()) {
Socket socket = serverSocket.accept();
threadNumber++;
System.out.println(threadNumber+"==========================");
socket.getOutputStream().write(("\"HTTP/1.1 200 OK\\r\\n\"Connection: close\r\n\r\n").getBytes());
// socket.getOutputStream().write("abrakadabra".getBytes());
socket.close();
Thread.sleep(1000);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
};
listenThread.start();
}
void stop() {
listenThread.interrupt();
}
}
上面的代码在一个客户请求后打印:
服务器已启动!
1 =========================
2 ==========================
当我将socket.getOutputStream().write(("\"HTTP/1.1 200 OK\\r\\n\"Connection: close\r\n\r\n").getBytes());
替换为socket.getOutputStream().write("abrakadabra".getBytes());
时,程序将打印:
服务器已启动!
1 =========================
2 ==========================
3 =========================