TCP 协议是传输层协议,有端口概念,可以基于此实现应用层 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
| import net from 'net'; const statusLine = 'HTTP/1.1 200 OK'; const resBody = '<h1>20240202</h1>'; const resHeader = [ 'Content-Type: text/html', `Content-Length: ${resBody.length}`, `Date: ${new Date().toUTCString()}`, ];
const res = [statusLine, ...resHeader, '', resBody].join('\r\n'); const tcp = net.createServer((socket) => { socket.on('data', (data) => { if (/GET/.test(data.toString())) { socket.write(res); } }); });
tcp.listen(3000, () => { console.log('server is running at http://localhost:3000'); });
|