Node.js와 Socket.io를 이용한 채팅 구현 (1)

김승엽
Berkbach
6 min readJun 23, 2018

--

Photo by rawpixel on Unsplash

🗂 목차

Socket.io?

socket.io란 실시간으로 상호작용하는 웹 서비스를 만드는 기술인 웹소켓을 쉽게 사용할 수 있게 해주는 모듈 입니다. socket.io 공식 홈페이지의 예제를 가지고 클라이언트가 채팅을 할 수 있는 웹을 만들어 보겠습니다.

Install

npm install --save socket.io

socket.io 모듈은 npm 명령어로 설치하면 됩니다.

app.js

/* socket\app.js */const app = require(‘express’)();const http = require(‘http’).createServer(app);const io = require(‘socket.io’)(http);
app.get(‘/’, (req, res) => { res.sendFile(__dirname + ‘/index.html’);});
io.on(‘connection’, (socket) => { console.log(‘a user connected’);
socket.on(‘chat message’, (msg) => { io.emit(‘chat message’, msg); });
socket.on(‘disconnect’, () => { console.log(‘user disconnected’); });});
http.listen(3000, () => { console.log(‘Connected at 3000’);});

app.js의 전체 코드 입니다. 보시면 알겠지만 http서버를 열고 socket.io서버를 http에 연결해줍니다. 이벤트 부분은 밑에서 html과 같이 설명하겠습니다.

index.html

/* socket\index.html */
<html>
<head> <meta charset=”utf-8"> <title>Socket</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom:
0;width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-
right:.5%; }
form button { width: 9%; background: rgb(130, 224, 255); border:
none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id=”messages”></ul> <form action=””> <input id=”m” autocomplete=”off” /><button>Send</button> </form> <script src=”/socket.io/socket.io.js”></script> <script src=”https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(() => { const socket = io(); $(‘form’).submit(() => { socket.emit(‘chat message’, $(‘#m’).val()); $(‘#m’).val(‘’); return false; });
socket.on(‘chat message’, (msg) => { $(‘#messages’).append($(‘<li>’).text(msg)); }); }); </script> </body></html>

head태그 안에 style은 css라서 신경 안써도 됩니다. 저희가 자세히 봐야할 부분은 script 태그 인데요.

<script src=”/socket.io/socket.io.js”></script><script src=”https://code.jquery.com/jquery-1.11.1.js"></script>

첫번째 줄은 socket.io, 두번째 줄은 jquery를 사용하기 위해서 적어주는 코드 입니다.

Event

전체 코드를 봤으니 이제 서버와 클라이언트를 번갈아 보면서 동작원리를 알아 보겠습니다. 이벤트는 emit(‘event’)으로 전달하면 on(‘event’)으로 받습니다.

왼쪽이 index.html(클라이언트), 오른쪽이 app.js(서버) 입니다.

index.html에서 const socket = io() 부분이 socket을 연결 해주는데요, 이 때 app.js에서 io.on(‘connection’)이벤트가 발생했습니다.

이와 같은 방식으로 $(‘form’).submit 의 콜백 함수로 socket.emit(‘chat message’)로 보냈으니까 socket.on(‘chat message’)의 콜백함수로 받습니다. emit할때 매개변수는 메시지 입니다. 마지막으로 클라이언트가 접속을 끊으면 on(‘disconnect’)이벤트가 발생합니다.

다음 시간에는 socket.io의 RoomNamespace를 알아보겠습니다.

--

--