Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

melius

[Node.js] TCP/IP 통신 본문

Node.js

[Node.js] TCP/IP 통신

melius102 2020. 1. 16. 10:49

디바이스 제어에 많이 사용되는 TCP/IP 통신을 Node.js의 내장모듈인 net을 이용하여 구현이 가능하다.

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

 

 

서버

const net = require('net');
const ipaddr = "localhost";
const port = 2031;

let server = net.createServer(function (socket) {
	console.log(socket.address().address + " connected.");

	// setting encoding
	socket.setEncoding('utf8');

	// print data from client
	socket.on('data', function (data) {
		console.log(data);
	});

	// print message for disconnection with client
	socket.on('close', function () {
		console.log('client disconnted.');
	});

	// send message to client
	setTimeout(() => {
		socket.write('welcome to server');
	}, 500);
	
	setTimeout(() => {
		socket.destroy();
	}, 3000);
});

// print error message
server.on('error', function (err) {
	console.log('err: ', err.code);
});

// listening
server.listen(port, ipaddr, function () {
	console.log('listening on 2031..');
});

 

클라이언트

const net = require('net');
const socket = net.connect({
	port: 2031,
	host: "localhost"
});

// setting encoding
socket.setEncoding('utf8');

socket.on('connect', function () {
	console.log('on connect');

	// send message to server
	setTimeout(() => {
		socket.write('msg from client');
	}, 1000);

	setTimeout(() => {
		// socket.destroy();
	}, 2000);
});

socket.on('data', function (data) {
	console.log(data);
});

socket.on('close', function () {
	console.log('close');
});

socket.on('error', function (err) {
	console.log('on error: ', err.code);
});

 

 

'Node.js' 카테고리의 다른 글

[Node.js] Addons  (0) 2021.03.08
[Node.js] JavaScript Runtime Environment  (0) 2021.02.27
[Node.js] Worker Threads  (0) 2020.02.04
[Node.js] FormData 객체 전송  (0) 2020.01.29
[Node.js] HTTPS 로컬 서버 구축  (0) 2020.01.29
Comments