실시간 채팅과 게임 서버
고성능 실시간 채팅 플랫폼과 멀티플레이어 게임 백엔드를 구축할 때의 과제와 해결책을 살펴봅니다.
실시간 채팅과 게임 서버은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Realtime Demands of Chat & Games
Live chat applications and multiplayer games are the epitome of realtime communication. They demand instant updates, low latency, and efficient data exchange between many users.
Traditional HTTP, with its request-response model, simply isn't suited for this constant, bidirectional flow of information. This is where WebSockets truly shine.
Tackling Latency & Throughput
One of the biggest challenges is ensuring low latency, meaning messages and game actions arrive almost instantly. High throughput is also crucial to handle many messages per second.
- Chat: Messages must appear immediately.
- Games: Player movements, attacks, and scores need to sync without noticeable delay.
WebSockets provide a persistent connection, minimizing overhead compared to repeated HTTP requests, which helps achieve these goals.
Managing Dynamic State
In both chat and games, the server needs to manage dynamic state. This includes:
- Which users are online.
- Who is in which chat room or game session.
- Player positions, health, and scores in a game.
- Recent chat history.
This state often resides in memory for speed but might be persisted to a database for recovery or long-term history.
Structuring with Rooms & Channels
To manage communication for many users, we often use rooms or channels. Instead of sending every message to every user, messages are routed to specific groups.
- A chat room for a specific topic.
- A game lobby or an active game instance.
This approach significantly reduces network traffic and server load by sending data only where it's needed.
Server: Joining a Chat Room
This Node.js example sets up a WebSocket server. Clients can send a joinRoom message to become part of a specific chat room. The server uses a Map to keep track of active rooms and their connected clients.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const rooms = new Map(); // Map: roomName -> Set<WebSocket>
wss.on('connection', ws => {
console.log('Client connected.');
ws.on('message', message => {
const msg = JSON.parse(message);
if (msg.type === 'joinRoom') {
const roomName = msg.room;
if (!rooms.has(roomName)) {
rooms.set(roomName, new Set());
}
rooms.get(roomName).add(ws);
ws.currentRoom = roomName; // Store room on connection
ws.send(`You joined: ${roomName}`);
console.log(`Client joined room '${roomName}'`);
}
});
ws.on('close', () => {
if (ws.currentRoom) {
rooms.get(ws.currentRoom).delete(ws);
if (rooms.get(ws.currentRoom).size === 0) {
rooms.delete(ws.currentRoom);
}
}
console.log('Client disconnected.');
});
ws.send('Send {\"type\": \"joinRoom\", \"room\": \"lobby\"}');
});
console.log('WebSocket server running on port 8080.');Broadcasting & Targeted Delivery
Once clients are in rooms, the server needs to efficiently send messages:
- Broadcast: To all clients in a specific room (e.g., a public chat message).
- Unicast: To a single, specific client (e.g., a private message or a game command for one player).
This targeted delivery is key to keeping the application responsive and preventing unnecessary data transfer.
Server: Broadcasting Chat Messages
Building on the room concept, this code shows how the server can receive a chat message and broadcast it to all other clients in the same room. Notice how it iterates through the Set of clients for the current room.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const rooms = new Map(); // Map: roomName -> Set<WebSocket>
wss.on('connection', ws => {
ws.on('message', message => {
const msg = JSON.parse(message);
if (msg.type === 'joinRoom') {
const roomName = msg.room;
if (!rooms.has(roomName)) {
rooms.set(roomName, new Set());
}
rooms.get(roomName).add(ws);
ws.currentRoom = roomName;
ws.send(`You joined: ${roomName}`);
} else if (msg.type === 'chat' && ws.currentRoom) {
const roomClients = rooms.get(ws.currentRoom);
roomClients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(`[${ws.currentRoom}] User says: ${msg.text}`);
}
});
}
});
ws.on('close', () => {
if (ws.currentRoom) {
rooms.get(ws.currentRoom).delete(ws);
if (rooms.get(ws.currentRoom).size === 0) {
rooms.delete(ws.currentRoom);
}
}
});
ws.send('Send {\"type\": \"joinRoom\", \"room\": \"lobby\"} then {\"type\": \"chat\", \"text\": \"Hello!\"}');
});
console.log('WebSocket server running on port 8080.');Client UI & Responsiveness
On the client-side (e.g., in a web browser), JavaScript uses the native WebSocket API to connect and handle messages. The UI is updated dynamically without page reloads.
This example shows a basic HTML structure and JavaScript to connect, join a room, and display incoming messages.
<!DOCTYPE html>
<html>
<head>
<title>Chat Client</title>
</head>
<body>
<div id="messages" style="border: 1px solid #ccc; height: 150px; overflow-y: scroll; padding: 5px;"></div>
<input type="text" id="chatInput" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<script>
const ws = new WebSocket('ws://localhost:8080');
const messagesDiv = document.getElementById('messages');
const chatInput = document.getElementById('chatInput');
ws.onopen = () => {
messagesDiv.innerHTML += '<p><em>Connected!</em></p>';
ws.send(JSON.stringify({ type: 'joinRoom', room: 'lobby' }));
};
ws.onmessage = event => {
messagesDiv.innerHTML += `<p>${event.data}</p>`;
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-scroll
};
function sendMessage() {
const text = chatInput.value;
if (text.trim() !== '') {
ws.send(JSON.stringify({ type: 'chat', text: text }));
chatInput.value = '';
}
}
</script>
</body>
</html>Game State Synchronization
For multiplayer games, game state synchronization is critical. This involves more than just chat messages; it's about continuously updating player positions, health, scores, and game events across all connected clients.
- Server as Authority: The server often acts as the single source of truth for the game state.
- Game Loop: A server-side game loop frequently calculates and broadcasts state changes to clients.
Techniques like interpolation and extrapolation on the client help smooth out visual updates despite network latency.
Key Realtime Challenges
Consider the typical requirements for building a robust live chat or multiplayer game server using WebSockets. Which of the following present significant challenges?
Recap: Building Realtime Apps
In this lesson, we explored the unique challenges of building live chat and multiplayer game servers with WebSockets. We learned:
- The critical need for low latency and high throughput.
- Strategies for managing dynamic state for users, rooms, and game entities.
- The importance of room-based messaging for efficient communication.
- How servers handle joining rooms, broadcasting messages, and how clients update their UI.
- The concept of game state synchronization for interactive experiences.
These principles form the foundation for creating engaging and responsive realtime applications.
AI 튜터와 함께 WebSockets & Realtime Systems Programming을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 47
자주 묻는 질문
“실시간 채팅과 게임 서버” 강의는 무료인가요?
네 — “실시간 채팅과 게임 서버” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“실시간 채팅과 게임 서버”에서 뭘 배우나요?
고성능 실시간 채팅 플랫폼과 멀티플레이어 게임 백엔드를 구축할 때의 과제와 해결책을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“실시간 채팅과 게임 서버” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 협업 편집기와 화이트보드
- 실시간 채팅과 게임 서버
- 실시간 데이터 대시보드
- 실시간 위치 추적 시스템 구축