今天老师让我们十分钟实现一个简单版的 Tomcat,需求很简单,用户访问 localhost:8080,能向后台发起请求。后台通过 socket 监听,并返回一个 html 页面内容给他就行,因为时间有限,只写了一个简单的类。
src目录放一个 text.html
运行结果如下
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * 服务器端
- *
- * @author 言曌
- * @date 2017-08-30 14:31
- */
- public class TomcatServer {
- public static void main(String[] args) throws Exception {
- ServerSocket server = new ServerSocket(8080);
- // (1) 接收新连接线程
- while (true) {
- try {
- // (1) 阻塞方法获取新的连接
- Socket socket = server.accept();
- // (2) 每一个新的连接都创建一个线程,负责读取数据
- new Thread(() -> {
- try {
- System.out.println("创建了新的线程:"+Thread.currentThread().getName());
- InputStreamReader r = new InputStreamReader(socket.getInputStream());
- BufferedReader br = new BufferedReader(r);
- String readLine = br.readLine();
- System.out.println("获取到数据:");
- System.out.println("====================================================》");
- while (readLine != null && !readLine.equals("")) {
- System.out.println(readLine);
- readLine = br.readLine();
- }
- String html = "http/1.1 200 ok\n\n" + readFromFile("test.html");
- PrintWriter pw = new PrintWriter(socket.getOutputStream());
- pw.println(html);
- pw.close();
- } catch (IOException e) {
- }
- }).start();
- } catch (IOException e) {
- }
- }
- }
- public static String readFromFile(String filename) {
- StringBuffer sb = new StringBuffer();
- try {
- BufferedReader br = new BufferedReader(new FileReader("/Users/liuyanzhao/sell/Demo/src/" + filename));
- String temp = null;
- while ((temp = br.readLine()) != null) {
- sb.append(temp + "\r\n");
- }
- // System.out.println(sb);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return sb.toString();
- }
- }
src目录放一个 text.html
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport"
- content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- </head>
- <body>
- <p>XXXXXXXXXX</p>
- <p>XXXXXXXXXXXXXXXXXXXX</p>
- <p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p>
- <p>这是 test.html 内容</p>
- </body>
- </html>
运行结果如下
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏