ServerSocketChannel 创建Http请求的服务器 ,写一个例子
时间: 2023-06-26 07:09:57 浏览: 51
好的,以下是一个使用 ServerSocketChannel 创建的简单 HTTP 服务器的示例代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpServerExample {
private static final int PORT = 8080;
private static final String RESPONSE_TEMPLATE = "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s";
private static final String RESPONSE_BODY = "<html><body><h1>Hello, World!</h1></body></html>";
private static final ByteBuffer RESPONSE_BUFFER = ByteBuffer.wrap(String.format(RESPONSE_TEMPLATE, RESPONSE_BODY.length(), RESPONSE_BODY).getBytes(StandardCharsets.UTF_8));
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(PORT);
serverSocketChannel.bind(address);
ExecutorService executorService = Executors.newFixedThreadPool(10);
while (true) {
SocketChannel socketChannel = serverSocketChannel.accept();
executorService.submit(() -> {
try {
ByteBuffer requestBuffer = ByteBuffer.allocate(1024);
socketChannel.read(requestBuffer);
String requestString = new String(requestBuffer.array(), StandardCharsets.UTF_8);
System.out.println(requestString);
socketChannel.write(RESPONSE_BUFFER);
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
}
```
这个简单的 HTTP 服务器监听端口 8080,每当接收到一个连接时,就会创建一个新的线程来处理该请求。处理请求的过程非常简单:读取请求,打印请求内容,并返回一个包含 "Hello, World!" 的 HTML 响应。请注意,这个示例并没有处理任何错误或异常情况,实际使用时需要注意这些情况。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)