feng xiaohan

TCP 实现 HTTP 服务

在传输层使用 TCP 一层去模拟返回应用层 HTTP 的报文。

后端(node)

import net from "net";

const html: string = `<h1>BLG</h1>`;

const header = [
  "HTTP/1.1 200 OK",
  "Content-Type: text/html",
  `Content-Length: ${html.length}`,
  "Date: Mon, 27 Jul 2009 12:28:53 GMT",
  `\r\n`,
  html,
];

const server = net.createServer((socket) => {
  socket.on("data", (data) => {
    console.log(data.toString());
    if (/GET/.test(data.toString())) {
      socket.write(headers.join("\r\n"));
      socket.end();
    }
  });
});

// 监听 TCP 服务
server.listen(8080, () => {
  console.log("server is running", server.address());
});