stream-based TCP servers/clients를 생성하기 위한 비동기 네트워크 API 제공
const net = require('net');
methods
method
description
net.createServer([options][, connectionListener])
creates a new TCP server. returns net.Server
net.connect(port[, host][, connectListener])
creates a new net.Socket. after connection, returns net.Socket
net.Server
method
description
server.listen()
Start a server listening for connections.
server.close([callback])
Stops the server from accepting new connections and keeps existing connections
event
description
close
Emitted when the server closes.
connection
Emitted when a new connection is made.
error
Emitted when an error occurs.
listening
Emitted when the server has been bound after calling server.listen().
net.Socket
method
description
socket.connect()
Start a server listening for connections.
socket.write(data[, encoding][, callback])
Sends data on the socket.
event
description
close
Emitted once the socket is fully closed.
connect
Emitted when a socket connection is successfully established.
data
Emitted when data is received.
error
Emitted when an error occurs.
example source code (Echo)
Server
constnet=require('net');constserver=net.createServer((connection)=>{// createServer는 net.Socket 클래스 반환console.log('client connected');connection.on('end',()=>{// client 커넥션이 끊기면 호출되는 이벤트console.log('client disconnected');});connection.pipe(connection);// 소켓의 데이터를 그대로 전달 (echo 역할)});server.listen(8090,()=>{// 다른 소켓의 접속 listeningconsole.log('server is listening');});
Client
constnet=require('net');constclient=net.connect({port:8090},()=>{// connect는 net.Socket 클래스 반환console.log("client connected");});client.write("client send data");// tx 버퍼에 data 쓰기client.on('data',(data)=>{// rx 버퍼에 데이터 읽어오기console.log("msg from server : "+data.toString());client.end();});client.on('end',()=>{// 연결 끊김 확인console.log("disconnected from server");});
Leave a comment