Socket.io는 웹 애플리케이션에서 실시간 통신을 가능하게 하는 JavaScript 라이브러리입니다. 실시간 알림 시스템을 구현하기 위해 Socket.io를 사용할 수 있습니다. 아래는 Socket.io를 사용하여 실시간 알림 시스템을 구현하는 예제입니다.
1. 서버에서 Socket.io 설치하기
먼저, 프로젝트에 Socket.io를 설치해야 합니다. Node.js 환경에서 다음 명령어를 사용하여 설치할 수 있습니다:
npm install socket.io
2. 서버 측 코드 작성하기
다음으로, 서버에서 Socket.io를 초기화하고 클라이언트와의 연결을 처리하는 코드를 작성해야 합니다. 다음은 간단한 예제입니다:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('A user connected');
// 클라이언트로부터의 알림 수신
socket.on('notification', (data) => {
console.log('Received notification:', data);
// 다른 클라이언트에 알림 전송
io.emit('notification', data);
});
// 연결 해제 시 처리
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
http.listen(3000, () => {
console.log('Server started on port 3000');
});
위 코드에서는 클라이언트의 ‘notification’ 이벤트를 수신하여 로그에 출력하고, 다른 클라이언트에게 ‘notification’ 이벤트를 전송합니다. 또한 클라이언트가 연결 끊을 때 ‘disconnect’ 이벤트를 처리하여 로그에 출력합니다.
3. 클라이언트 측 코드 작성하기
이제 클라이언트에서도 Socket.io를 사용하여 알림을 보내고 받을 수 있도록 코드를 작성해야 합니다. 다음은 클라이언트 측 코드의 예입니다:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
// 알림 전송
function sendNotification() {
var data = {
message: 'New notification',
timestamp: Date.now()
};
socket.emit('notification', data);
}
// 알림 수신
socket.on('notification', function(data) {
console.log('Received notification:', data);
// 알림을 표시하는 로직 추가
});
</script>
위 코드에서는 ‘notification’ 이벤트를 통해 알림을 보내고 받을 수 있습니다. 클라이언트에서 sendNotification() 함수를 호출하여 알림을 보낼 수 있으며, 서버에서 ‘notification’ 이벤트를 받아 알림을 수신할 수 있습니다.
위 예제를 기반으로 필요에 따라 서버와 클라이언트 코드를 변경하여 실시간 알림 시스템을 구현할 수 있습니다. Socket.io는 실시간 통신에 편리한 기능들을 제공하므로 다양한 기능을 추가할 수도 있습니다.
더 자세한 정보와 예제 코드는 Socket.io 공식 문서를 참고하십시오.