본문 바로가기
프론트엔드

초간단 서버 클라이언트 예시

by 느바 2025. 1. 3.
반응형

초간단 서버 클라이언트 예시

 

서버와 클라이언트 이해를 위해 초 간단 예시를 만들어본다.

Step 1. node 설치

node를 설치하지 않았다면 설치한다.

설치유무는 터미널에서 node -v 를 입력하면 알 수 있다.

node -v

Step 2. 파일 구조

'my-server', 'my-client' 라는 폴더를 만들고 각각 index.js를 생성한다.

Step 3. 서버 제작

my-server/index.js 에서는

node의 http모듈을 가져와 server 인스턴스를 만들고, server가 3000번 포트를 열어 요청을 기다리는 기능을 만든다.

const http = require("http"); // node의 http 모듈 가져오기
const content = `
HTTP Lecture
`;
const handler = (req, res) => { // web server 로 요청이 들어오면 처리할 함수
    res.write(content); // 요청한 클라이언트에게 데이터 전달
    res.end();          // 종료 응답을 클라이언트에게 보냄
};

const server = http.createServer(handler);  // server 인스턴스 생성
server.listen(3000, () => console.log("server running"));// server가 3000번 포트를 열고 요청을 대기하게 됨

Step 4. 클라이언트 제작

my-client/index.js 에서는

마찬가지로 node의 http 모듈을 가져오고, 서버로 부터 받은 응답을 처리하는 기능을 만든다. 여기서는 간단히 서버가 보낸 데이터를 보여주는 기능을 만든다.

const http = require('http');

const options = new URL("http://localhost:3000/");

const handler = (res) => {  // 응답을 처리하는 핸들러
    const data = [];
    res.on("data", (chunk) => {
        data.push(chunk.toString());
    });
    res.on("end", () => {
        console.log(data.join(""));
    })
};

const req = http.request(options, handler);
req.end();

Step 5. 실행

터미널에서

node my-server 를 입력하면, 서버가 가동된다.(localhost:3000)

node my-server

또다른 터미널을 열어

node my-client 를 입력하면 서버에서 보낸 데이터가 출력되는 것을 확인할 수 있다.

node my-client

 

반응형

'프론트엔드' 카테고리의 다른 글

Vite 프로젝트 설정 파일 vite.config.js  (1) 2025.01.17
Vite 사용법  (1) 2025.01.17
Eclipse vs Visual Studio Code (VS Code) 비교  (0) 2025.01.01
Apache Tomcat과 Live Server의 비교  (1) 2025.01.01
윈도우에 톰캣 설치  (0) 2025.01.01