用上面的http服务器实现一个例子
时间: 2024-02-16 11:00:43 浏览: 18
好的,以下是一个使用上述HTTP服务器的例子。在这个例子中,当你在浏览器中访问`http://localhost:8080`时,服务器会返回一个"Hello world!"的HTTP响应。
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080); // 创建服务器套接字并绑定到8080端口
System.out.println("Server started.");
while (true) {
Socket client = server.accept(); // 等待客户端连接
System.out.println("Client connected.");
String response = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello world!"; // 构造HTTP响应
OutputStream out = client.getOutputStream();
out.write(response.getBytes()); // 发送响应给客户端
out.flush();
client.close(); // 关闭客户端连接
System.out.println("Client disconnected.");
}
}
}
```
在命令行中运行这段代码,然后在浏览器中访问`http://localhost:8080`,你应该会在浏览器中看到一个"Hello world!"的页面。