이번에는 Node.js와 Socket.IO를 활용하여 채팅 서버를 구축하는 방법에 대해 알아보겠습니다.
이 글에서는 필수적으로 알아야 할 다섯 가지 핵심 요소를 다루겠습니다!
https://github.com/socketio/socket.io
GitHub - socketio/socket.io: Realtime application framework (Node.JS server)
Realtime application framework (Node.JS server). Contribute to socketio/socket.io development by creating an account on GitHub.
github.com
1. Socket.IO 기본 설정 및 연결
Socket.IO는 Node.js에서 실시간 양방향 통신을 가능하게 해주는 라이브러리입니다. 클라이언트와 서버 간의 실시간 데이터 전송을 위해 Socket.IO를 설정하고 클라이언트의 연결을 처리하는 기본적인 방법을 소개합니다.
[라이브러리 설치]
> npm install socket.io
[서버 설정]
const http = require('http');
const socketIo = require('socket.io');
// HTTP 서버 생성
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Socket.IO Chat Server');
});
// Socket.IO 서버 생성
const io = socketIo(server);
// 클라이언트가 연결될 때마다 실행되는 코드
io.on('connection', (socket) => {
console.log('A user connected');
// 사용자가 연결 해제될 때 실행되는 코드
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
// 서버가 3000번 포트에서 리스닝 시작
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
2. 이벤트 핸들링
Socket.IO는 이벤트 기반 라이브러리로, 특정 이벤트를 수신하고 처리하는 것이 핵심입니다. 클라이언트와 서버 간에 메시지를 주고받기 위해 다양한 이벤트를 정의하고 핸들러를 설정할 수 있습니다.
[이벤트 처리 예제]
io.on('connection', (socket) => {
console.log('A user connected');
// 'chat message' 이벤트를 수신했을 때 실행되는 코드
socket.on('chat message', (msg) => {
console.log('Message received: ' + msg); // 수신한 메시지 로그 출력
io.emit('chat message', msg); // 모든 클라이언트에게 메시지 브로드캐스트
});
// 사용자가 연결 해제될 때 실행되는 코드
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
3. 네임스페이스와 룸
네임스페이스와 룸은 Socket.IO의 대표적인 기능으로, 클라이언트를 그룹화하여 효율적으로 관리할 수 있습니다.
- namespace: 네임스페이스를 사용하면 서로 다른 애플리케이션 논리를 분리할 수 있습니다.
// '/chat' 네임스페이스 생성
const chatNamespace = io.of('/chat');
chatNamespace.on('connection', (socket) => {
console.log('A user connected to /chat namespace');
});
const chatNamespace = io.of('/alarm');
chatNamespace.on('connection', (socket) => {
console.log('User connected to /alarm namespace');
});
- room: 룸은 같은 네임스페이스 내에서 클라이언트를 그룹화하는 방법입니다.
io.on('connection', (socket) => {
// 'room1' 룸에 사용자 추가
socket.join('room1');
// 'room1' 룸에 있는 모든 사용자에게 메시지 전송
socket.to('room1').emit('message', 'Welcome to Room 1');
// 'leave room1' 이벤트를 수신했을 때 실행되는 코드
socket.on('leave room1', () => {
socket.leave('room1'); // 사용자를 'room1'에서 제거
});
});
4. 에러 핸들링
실시간 애플리케이션에서는 다양한 종류의 오류가 발생할 수 있습니다. 이러한 오류를 적절하게 처리하여 안정성을 유지하는 것이 중요합니다.
[에러 핸들링 예제]
io.on('connection', (socket) => {
// 소켓에서 오류가 발생했을 때 실행되는 코드
socket.on('error', (err) => {
console.error('Socket error:', err);
});
// 'chat message' 이벤트를 수신했을 때 실행되는 코드
socket.on('chat message', (msg) => {
try {
// 메시지 처리 로직
} catch (error) {
console.error('Message handling error:', error);
socket.emit('error', 'Message processing failed');
}
});
});
5. 보안
보안은 실시간 애플리케이션에서 매우 중요합니다. 사용자 인증과 데이터 암호화를 통해 보안을 강화할 수 있습니다.
[인증 예제]
// 인증 미들웨어 설정
io.use((socket, next) => {
const token = socket.handshake.auth.token; // 핸드셰이크에서 인증 토큰 가져오기
if (isValidToken(token)) { // 토큰 유효성 검사
next(); // 인증 성공 시 다음 미들웨어로 이동
} else {
next(new Error('authentication error')); // 인증 실패 시 에러 반환
}
});
[SSL/TLS 설정]
SSL/TLS를 사용하여 데이터를 암호화합니다.
// SSL/TLS 설정
const fs = require('fs');
const https = require('https');
const socketIo = require('socket.io');
// HTTPS 서버 생성
const server = https.createServer({
key: fs.readFileSync('path/to/private.key'), // SSL 키 파일 경로
cert: fs.readFileSync('path/to/certificate.crt') // SSL 인증서 파일 경로
});
// Socket.IO 서버 생성
const io = socketIo(server);
// HTTPS 서버가 3000번 포트에서 리스닝 시작
server.listen(3000, () => {
console.log('Secure server is listening on port 3000');
});
이번 글을 통해 Node.js와 Socket.IO를 사용하여 기본적인 채팅 서버를 구축하는 방법을 정리해 보았습니다.
이글을 기반으로 다양한 기능을 추가해 더 좋은 애플리케이션을 만들 수 있으실 겁니다!
더 자세한 정보는 Socket.IO 공식 문서를 참고하시기 바랍니다.
https://socket.io/docs/v4/
Introduction | Socket.IO
If you are new to Socket.IO, we recommend checking out our tutorial.
socket.io
'스터디-ing > Programming' 카테고리의 다른 글
[Electron] electron-updater checksum mismatch (0) | 2024.05.31 |
---|---|
[Java] Spring으로 S3 Signed URL 발급 받기 (0) | 2024.05.24 |
[Javascript] Google reCAPTCHA (0) | 2024.05.23 |
[Electron] 자동 업데이트 electron-updater(with Github) (0) | 2022.04.15 |