SX - 1

  1. public static void main(String[] args) throws IOException {
  2. //http://localhost:8192/tcp/web/index.html
  3. ServerSocket bs = new ServerSocket(8192);//创建服务器套接字
  4. /*
  5. * 浏览器解析服务器回写的html页面,如果页面中有图片,那么浏览器会单独开一个线程读取服务
  6. * 器的图片,我们让服务器一直处于监听状态,客户端请求一次,服务器回写一次。
  7. */
  8. while (true) {
  9. Socket cs = bs.accept();
  10. //开启多线程
  11. new Thread(() -> {
  12. try {
  13. InputStream is = cs.getInputStream();
  14. //GET /tcp/web/index.html HTTP/1.1
  15. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  16. String line = br.readLine();
  17. String[] arr = line.split(" ");
  18. String htmlPath = arr[1].substring(1);
  19. //读取服务器上的HTML文件并写到客户端(浏览器)
  20. FileInputStream fis = new FileInputStream(htmlPath);
  21. OutputStream os = cs.getOutputStream();
  22. //写入HTTP协议响应头,固定写死
  23. os.write("HTTP/1.1 200 ok\r\n".getBytes());
  24. os.write("Content-Type:text/html\r\n".getBytes());
  25. //必须写入空行,否则浏览器不执行
  26. os.write("\r\n".getBytes());
  27. byte[] bytes = new byte[1024];
  28. int len;
  29. while ((len = fis.read(bytes)) != -1) {
  30. os.write(bytes,0,len);
  31. }
  32. fis.close();
  33. cs.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }).start();
  38. }
  39. }

HTML示例

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>index</title>
  8. <link rel="shortcut icon" href="img/favicon.ico"/>
  9. </head>
  10. <body>
  11. 服务器页面<br/>
  12. <img src="img/seata.png">
  13. </body>
  14. </html>

favicon.png seata.png
favicon.ico seata.png