본문 바로가기

etc

직접 구현하면서 배우는 http 프로토콜

전체 코드

const PORT = 8080;
const IP = "localhost";
const net = require('node:net');

//tcp 연결 요청
const client = net.createConnection(PORT, IP, () => {
    // GET 메소드
    client.write('GET /test HTTP/1.1\r\nHost: localhost:8080\r\nConnection: keep-alive\r\n\r\n');
    // POST 메소드
    client.write('POST /test HTTP/1.1\r\nHost: localhost:8080\r\nContent-Type: application/json\r\nContent-Length: 14\r\n\r\n{"test":"test"}');

    //Connection: keep-alive 커넥션을 바로 종료하지 않고 유지 시킴
});


client.on('data', (data) => {
    console.log(data.toString());
    client.end();
});

client.on('close', () => {
    console.log("연결 종료")
})

 

http 프로토콜의 과정은

1. tcp 연결

2. 헤더 + 바디 정보 전달

3. 서버 응답

4. tcp 연결 종료

의 과정으로 진행이 됩니다.

 

구현하기 앞서서 node의 공식문서에 가서 net모듈의 createConnetion 메소드의 사용 방법을 한번 알아보는 것도 좋을 것 같습니다.

https://nodejs.org/api/net.html#netcreateconnection

 

Net | Node.js v21.6.1 Documentation

Net# Source Code: lib/net.js The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()). It can be accessed using: const net = require('node:net'); copy IP

nodejs.org

공식문서에 있는 createConnection의 예제 입니다.

const net = require('node:net');
const client = net.createConnection({ port: 8124 }, () => {
  // 'connect' listener.
  console.log('connected to server!');
  client.write('world!\r\n');
});
client.on('data', (data) => {
  console.log(data.toString());
  client.end();
});
client.on('end', () => {
  console.log('disconnected from server');
});

 

조금의 수정을 통해 사용하기 좋게 만들었습니다.

const PORT = 8080;
const IP = "localhost";
const net = require('node:net');

//tcp 연결 요청
const client = net.createConnection(PORT, IP, () => {
});


client.on('data', (data) => {
    console.log(data.toString());
    client.end();
});

client.on('close', () => {
    console.log("연결 종료")
})

 

가장 기본적인 GET Method의 경우

const client = net.createConnection(PORT, IP, () => {
    // GET 메소드
    client.write('GET /test HTTP/1.1\r\nHost: localhost:8080\r\n\r\n');
});

메소드, url, http 프로토콜, 호스트 정보만 있으면 요청이 가능합니다.

요청 결과

POST Method의 경우 

const client = net.createConnection(PORT, IP, () => {
    // POST 메소드
    client.write('POST /test HTTP/1.1\r\nHost: localhost:8080\r\nContent-Type: application/json\r\nContent-Length: 14\r\n\r\n{"abc":"test"}');
});

 

 

위와 같이 사용할 수 있습니다.

header에 keep-alive를 추가해준다면 tcp연결이 종료되지 않고 데이터를 주고 받을 수 있습니다.

const client = net.createConnection(PORT, IP, () => {
    // GET 메소드
    client.write('GET /test HTTP/1.1\r\nHost: localhost:8080\r\nConnection: keep-alive\r\n\r\n');
    // POST 메소드
    client.write('POST /test HTTP/1.1\r\nHost: localhost:8080\r\nContent-Type: application/json\r\nContent-Length: 14\r\n\r\n{"abc":"test"}');

    //Connection: keep-alive 커넥션을 바로 종료하지 않고 유지 시킴
});