核心操作:
① socket解除阻塞时为新请求进入,使用线程
解决多请求并发问题
② IO流的处理:客户端路径获取使用字符流
,服务端响应给浏览器使用字节流
③ 响应行、响应头、响应正文
的处理(遵循HTTP协议),使自写服务器可以正确被浏览器解析响应的内容
源码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public class MyTomcatServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8080); while (true) { Socket socket = serverSocket.accept(); new Thread(() -> service(socket)).start(); } } catch (Exception e) { e.printStackTrace(); } }
public static void service(Socket socket) { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = bufferedReader.readLine(); String[] requestInfos = line.split(" "); String requestURL = requestInfos[1]; System.out.println(requestURL);
int length = "/demo/".length(); requestURL = requestURL.substring(length);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(requestURL)); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write("HTTP/1.1 200 OK\r\n".getBytes());
bos.write("Content-Type:text/html\r\n".getBytes()); bos.write("\r\n".getBytes());
int len = -1; byte[] bys = new byte[8192]; while ((len = bis.read(bys)) != -1) { bos.write(bys, 0, len); } bis.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); } } }
|
页面测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body>
<h2>首页</h2>
<img src="001.jpg" alt="图片1" width="300px"> <img src="002.jpg" alt="图片2" width="300px">
</body> </html>
|