SX - 1
public static void main(String[] args) throws IOException {//http://localhost:8192/tcp/web/index.htmlServerSocket bs = new ServerSocket(8192);//创建服务器套接字/** 浏览器解析服务器回写的html页面,如果页面中有图片,那么浏览器会单独开一个线程读取服务* 器的图片,我们让服务器一直处于监听状态,客户端请求一次,服务器回写一次。*/while (true) {Socket cs = bs.accept();//开启多线程new Thread(() -> {try {InputStream is = cs.getInputStream();//GET /tcp/web/index.html HTTP/1.1BufferedReader br = new BufferedReader(new InputStreamReader(is));String line = br.readLine();String[] arr = line.split(" ");String htmlPath = arr[1].substring(1);//读取服务器上的HTML文件并写到客户端(浏览器)FileInputStream fis = new FileInputStream(htmlPath);OutputStream os = cs.getOutputStream();//写入HTTP协议响应头,固定写死os.write("HTTP/1.1 200 ok\r\n".getBytes());os.write("Content-Type:text/html\r\n".getBytes());//必须写入空行,否则浏览器不执行os.write("\r\n".getBytes());byte[] bytes = new byte[1024];int len;while ((len = fis.read(bytes)) != -1) {os.write(bytes,0,len);}fis.close();cs.close();} catch (IOException e) {e.printStackTrace();}}).start();}}
HTML示例
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title><link rel="shortcut icon" href="img/favicon.ico"/></head><body>服务器页面<br/><img src="img/seata.png"></body></html>

favicon.ico seata.png
