JavaSE 手写 Web 服务器(一) (3)

改造 Server 类:

public class Server { private ServerSocket server; public static void main(String[] args) { Server server = new Server(); server.start(); } /** * 启动服务器 */ public void start() { try { server = new ServerSocket(8080); // 接收数据 this.receiveData(); } catch (IOException e) { e.printStackTrace(); } } /** * 接收数据 */ private void receiveData() { try { Socket client = this.server.accept(); // 读取客户端发送的数据 Request request = new Request(client.getInputStream()); // 响应数据 Response response = new Response(client.getOutputStream()); response.println("<!DOCTYPE html>") .println("<html lang=\"zh\">") .println(" <head> ") .println(" <meta charset=\"UTF-8\">") .println(" <title>测试</title>") .println(" </head> ") .println(" <body> ") .println(" <h3>Hello " + request.getParameter("username") + "</h3>")// 获取登陆名 .println(" </body> ") .println("</html>"); response.pushToClient(200); } catch (IOException e) { e.printStackTrace(); } } /** * 关闭服务器 */ public void stop() { } }

使用 post 请求方式提交表单,返回结果结果如下:

image

五、多线程

目前,程序启动后每接收一次请求,程序就会运行中断,这样就没法处理下个客户端请求。

因此,我们需要使用多线程处理多个客户端的请求。

创建一个 Runnable 处理客户端请求:

public class Dispatcher implements Runnable { // socket 客户端 private Socket socket; // 请求对象 private Request request; // 响应对象 private Response response; // 响应码 private int code = 200; public Dispatcher(Socket socket) { this.socket = socket; try { this.request = new Request(socket.getInputStream()); this.response = new Response(socket.getOutputStream()); } catch (IOException e) { code = 500; return; } } @Override public void run() { this.response.println("<!DOCTYPE html>") .println("<html lang=\"zh\">") .println(" <head> ") .println(" <meta charset=\"UTF-8\">") .println(" <title>测试</title>") .println(" </head> ") .println(" <body> ") .println(" <h3>Hello " + request.getParameter("username") + "</h3>")// 获取登陆名 .println(" </body> ") .println("</html>"); try { this.response.pushToClient(code); this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } }

改造 Server 类:

public class Server { private ServerSocket server; private boolean isShutdown = false; public static void main(String[] args) { Server server = new Server(); server.start(); } /** * 启动服务器 */ public void start() { try { server = new ServerSocket(8080); // 接收数据 this.receiveData(); } catch (IOException e) { this.stop(); } } /** * 接收数据 */ private void receiveData() { try { while(!isShutdown) { new Thread(new Dispatcher(this.server.accept())).start(); } } catch (IOException e) { this.stop(); } } /** * 关闭服务器 */ public void stop() { isShutdown = true; try { this.server.close(); } catch (IOException e) { e.printStackTrace(); } } }

现在,不管浏览器发送几次请求,服务端程序都不会中断了。

六、参考资料

未完待续。。。。。。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwgxgd.html