Node.js에서 Socket.IO 구현하기
Express 애플리케이션에 Socket.IO를 통합하여 양방향 이벤트 기반 통신을 구현합니다.
Node.js에서 Socket.IO 구현하기은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 6개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Meet Socket.IO
In the previous lesson, we learned about WebSockets for real-time communication. While powerful, raw WebSockets can be complex to manage, especially with connection stability and fallback options.
This is where Socket.IO comes in! It's a library that enables real-time, bi-directional, and event-based communication between web clients and servers. It works on every platform, browser, and device, ensuring reliable connections.
- Abstraction: Simplifies WebSocket API.
- Reliability: Handles disconnections and re-connections.
- Fallback: Uses HTTP long-polling if WebSockets aren't available.
- Broadcasting: Easily send messages to multiple clients.
Project Setup
First, let's prepare our project. We'll need Node.js and npm installed. Open your terminal and create a new project folder.
Inside your new folder, initialize a Node.js project and then install the necessary packages: express for our web server and socket.io for real-time communication.
npm init -ynpm install express socket.io
Our Base: Express Server
Before integrating Socket.IO, let's set up a basic Express server. This server will handle our HTTP requests and also serve as the foundation for our real-time communication.
Create a file named server.js and add the following code. This sets up an Express app that listens on port 3000.
const express = require('express');
const http = require('http'); // Needed for Socket.IO
const app = express();
const server = http.createServer(app); // Create HTTP server
const PORT = 3000;
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Attach Socket.IO
Now, let's attach Socket.IO to our existing Express HTTP server. This allows Socket.IO to listen for WebSocket connections on the same port as our web server.
We import the socket.io library and pass our http server instance to it. This creates a Socket.IO server instance, conventionally named io.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io'); // Import Server class
const app = express();
const server = http.createServer(app);
const io = new Server(server); // Attach Socket.IO to HTTP server
const PORT = 3000;
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Client Connection Events
The most fundamental event in Socket.IO is 'connection'. This event fires every time a new client successfully connects to the Socket.IO server.
Inside this event listener, you get a socket object, which represents the individual client. You can then listen for specific events from that client or send messages directly to it.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const PORT = 3000;
// Listen for incoming connections
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Listen for disconnection
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Server Emits Events
The server can send (or 'emit') custom events to clients. To send a message to a specific client who just connected, we use socket.emit().
This method takes an event name (e.g., 'welcome') and any data you want to send along with it. The client will then listen for this specific event.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const PORT = 3000;
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Send a 'welcome' event to the newly connected client
socket.emit('welcome', `Welcome, your ID is ${socket.id}!`);
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Server Receives Events
Just as the server can emit events, it can also listen for events sent from clients. We use socket.on() for this, similar to how we listened for 'connection'.
When a client sends an event with a specific name, the corresponding server-side listener will execute, receiving any data the client sent.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const PORT = 3000;
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.emit('welcome', `Welcome, your ID is ${socket.id}!`);
// Listen for a 'clientMessage' event from this specific client
socket.on('clientMessage', (message) => {
console.log(`Message from ${socket.id}: ${message}`);
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Client-Side Interaction
To connect to our Socket.IO server, the client needs the Socket.IO client library. You can include it via a CDN or npm.
This HTML snippet shows a basic client that connects, listens for the 'welcome' event, and sends a 'clientMessage' event to the server. Save this as index.html.
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Client</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Socket.IO Client</h1>
<p id="status">Connecting...</p>
<button onclick="sendMessage()">Send Hello</button>
<ul id="messages"></ul>
<script>
const socket = io('http://localhost:3000'); // Connect to your server
socket.on('connect', () => {
document.getElementById('status').innerText = 'Connected to server!';
console.log('Connected to server!');
});
socket.on('welcome', (msg) => {
const item = document.createElement('li');
item.innerText = `Server: ${msg}`;
document.getElementById('messages').appendChild(item);
console.log('Received from server:', msg);
});
socket.on('disconnect', () => {
document.getElementById('status').innerText = 'Disconnected.';
console.log('Disconnected from server.');
});
function sendMessage() {
const msg = 'Hello from client!';
socket.emit('clientMessage', msg);
const item = document.createElement('li');
item.innerText = `Client: ${msg}`;
document.getElementById('messages').appendChild(item);
}
</script>
</body>
</html>Broadcasting Messages
Often, you need to send a message to *all* connected clients, not just the one that triggered an event. This is called broadcasting.
Instead of socket.emit(), which sends to a specific socket, we use io.emit() to send to everyone connected to the Socket.IO server.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const PORT = 3000;
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.emit('welcome', `Welcome, your ID is ${socket.id}!`);
// Broadcast to all clients (except the sender) when a new user connects
socket.broadcast.emit('user joined', `User ${socket.id} joined.`);
socket.on('clientMessage', (message) => {
console.log(`Message from ${socket.id}: ${message}`);
// Broadcast the message to ALL connected clients
io.emit('serverMessage', `[${socket.id}] ${message}`);
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
// Broadcast to all clients when a user disconnects
io.emit('user left', `User ${socket.id} left.`);
});
});
app.get('/', (req, res) => {
res.send('<h1>Hello from Express!</h1>');
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Quick Check: Event Scope
You've seen how to send messages using both socket.emit() and io.emit(). Which method would you use to send a message to *all* connected clients?
Recap: Socket.IO Integration
Excellent work! In this lesson, you've learned to integrate Socket.IO into your Node.js Express application, enabling powerful real-time features.
- Setup: Installed
expressandsocket.io. - Server: Attached Socket.IO to an existing HTTP server.
- Connections: Handled client
'connection'and'disconnect'events. - Communication: Used
socket.emit()to send to specific clients andio.emit()for broadcasting to all clients. - Listeners: Set up
socket.on()to receive custom events from clients.
You now have the foundation to build interactive, real-time applications!
자주 묻는 질문
“Node.js에서 Socket.IO 구현하기” 강의는 무료인가요?
네 — “Node.js에서 Socket.IO 구현하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.
“Node.js에서 Socket.IO 구현하기”에서 뭘 배우나요?
Express 애플리케이션에 Socket.IO를 통합하여 양방향 이벤트 기반 통신을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 3번째 강의입니다.
“Node.js에서 Socket.IO 구현하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- WebSockets 입문
- NestJS를 사용한 WebSockets
- Node.js에서 Socket.IO 구현하기
- 게이트웨이 구성
- 실시간 채팅 애플리케이션 만들기
- 실시간 채팅 애플리케이션