
1. 개요
Node.js에서 net 모듈을 사용하여 Server와 Client 간의 간단한 통신을 해보는 예제이다.
2. 서버 코드
net 모듈을 선언하고 net.createServer()로 server 객체를 생성하고 요청에 대한 서비스를 만든다.
var net = require('net');
var server = net.createServer(function(socket) {
서버에 연결이 되면 메세지와 1증가한 카운트값을 전송한다.
socket.write('[from Server] message.\r\n');
socket.write("[from Server] count = " + count);
socket.pipe(socket);
연결이 종료되면 아래의 로그를 출력한다.
socket.on('end', function() {
console.log('[Server] Connection End');
})
서버 전체 코드이다.
/** net : server */
var net = require('net');
var count = 0;
var server = net.createServer(function(socket) {
console.log('[Server] Connection Start');
count++;
socket.on('end', function() {
console.log('[Server] Connection End');
});
socket.write('[from Server] message.\r\n');
socket.write("[from Server] count = " + count);
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
console.log('http://127.0.0.1:1337/');
실행결과
요청이 들어오고 종료할때마다 Start, End로그가 반복적으로 출력된다.

3. 클라이언트 코드
아래와 같이 1337 포트로 클라이언트 연결을 생성한다.
var client = net.connect({ port : 1337 }, function() {
서버로 부터 전송된 데이터를 로그로 출력하고 연결을 종료한다.
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
클라이언트에서 연결이 종료되면 아래이 로그를 출력한다.
client.on('end', function() {
console.log('[Client] Disconnected from Server');
});
클라이언트 전체 코드이다.
/** net : client */
var net = require('net');
var client = net.connect({ port : 1337 }, function() {
console.log('[Client] Connected to Server!');
});
client.on('end', function() {
console.log('[Client] Disconnected from Server');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
실행결과
요청마다 서버로부터 메세지와 카운트 값을 받아서 로그로 출력한다.
[Client] Connected to Server!
[from Server] message.
[from Server] count = 1
[Client] Disconnected from Server
[Client] Connected to Server!
[from Server] message.
[from Server] count = 2
[Client] Disconnected from Server
4. PuTTY에서 접속
주소에 로컬PC의 IP(또는 127.0.0.1)를 입력하고 Connection type은 Telnet을 선택하고 포트는 1337을 입력한다.

PuTTY에서의 요청은 서버로부터 받은 메세지와 카운트 값만을 출력하고 있다.

728x90
'■ Front-End ■ > Node.js' 카테고리의 다른 글
[Node.js] http 모듈로 text와 html을 브라우저에 표시해보자. (0) | 2023.02.26 |
---|---|
[Node.js] socket.io 모듈을 사용하여 소켓통신을 구현해 보자. (0) | 2023.02.26 |
[Node.js] fs 모듈을 사용하여 파일을 읽고 쓰기 (0) | 2023.02.26 |
[Node.js] process에 이벤트를 생성하고 호출해 보자. (0) | 2023.02.26 |
[Node.js] querystring 모듈을 사용하여 쿼리스트링 파싱 (0) | 2023.02.26 |
댓글