模式解释
一个请求一个线程来进行处理,类似早期的BIO服务器网络模型。
优点
多个请求可以并发执行,提高了效率
示例 BIO的网络编程模型
实现浏览器访问服务器,服务器给页面输出hello world + new Date()
服务器
/**
* 服务器端
* @Author: puhaiguo
* @Date: 2022-07-11 23:30
* @Version 1.0
*/
public class MyServer extends Thread{
private int port;
public MyServer(int port) {
this.port = port;
}
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(port);
/*注意Myservice里面是线程安全,不要出现共享变量的操作*/
MyService myService = new MyService();
/*循环监听socket连接*/
while (true){
/*接收客户端连接*/
Socket accept = serverSocket.accept();
/*开辟一个线程去执行客户端的任务*/
new Thread(()->{
try {
myService.service(accept);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
请求处理类
/**
* 处理类
* @Author: puhaiguo
* @Date: 2022-07-11 23:33
* @Version 1.0
*/
public class MyService {
public void service(Socket socket) throws IOException {
/*获取输出流*/
OutputStream outputStream = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
try {
dataOutputStream.writeBytes("HTTP/1.0 200 OK\r\n");
dataOutputStream.writeBytes("Content-type:text/html\r\n");
dataOutputStream.writeBytes("\r\n");
dataOutputStream.writeBytes("<html><head><title>足球小子服务器</title></head><body>");
for (int i = 0; i < 10; i++) {
dataOutputStream.writeBytes("hello world " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:HH:ss")));
dataOutputStream.writeBytes("<br>\r\n");
TimeUnit.SECONDS.sleep(1);
/*强制刷新*/
dataOutputStream.flush();
}
dataOutputStream.writeBytes("</body></html>");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
outputStream.close();
socket.close();
}
}
}
测试
/**
* 测试我的服务器
* @Author: puhaiguo
* @Date: 2022-07-11 23:43
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
MyServer myServer = new MyServer(80);
myServer.start();
}
}
结论
呃虽然实现了并发,但是这个是一个很简易的实验,在处理客户端socket的时候 可以加一个**线程池、NIO、多路复用 **等高级优化。