(Term) Socket이란?

Su Bak
4 min readJun 6, 2020

개발을 하다보면 여러 용어를 접하게 되는데요. 그 중 이번 글에선 소켓(socket)이란 무엇인지에 대해 간단히 소개하고자 합니다.

소켓(Socket)이란 네트워크상에서 동작하는 프로그램 간 통신의 종착점(Endpoint)입니다. 즉, 프로그램이 네트워크에서 데이터를 통신할 수 있도록 연결해주는 연결부라고 할 수 있습니다.

Endpoint : IP Address와 port 번호의 조합을 뜻하며 최종 목적지를 나타냅니다. 예시로 최종목적지는 사용자의 디바이스(PC, 스마트폰 등) 또는 Server가 될 수 있습니다.

데이터를 통신할 수 있도록 해주는 연결부이기 때문에 통신할 두 프로그램(Client, Server) 모두에 소켓이 생성되야 합니다.

Server는 특정 포트와 연결된 소켓(Server 소켓)을 가지고 컴퓨터 위에서 동작하게 되는데요. 이 Server는 소켓을 통해 Cilent측 소켓의 연결 요청이 있을 때까지 기다리고 있습니다(listening 한다 라고도 표현합니다).

Client 소켓에서 연결요청을 하면(올바른 port로 들어왔을 때) Server 소켓이 허락을 하여 통신을 할 수 있도록 연결(connection)되는 것입니다.

아래는 Socket.IO 문서에 나오는 Server를 구현하는 예시 코드입니다.

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
});
}

io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});

코드를 보시면 HTTP Server를 생성하여 80번 port를 연결하여(bind하여) 해당 Endpoint로 Client의 요청을…

--

--

Su Bak

Backend Developer. Mainly use JavaScript but try not to have language constraints. Always trying to acquire new knowledge