Trong tutorial này, chúng ta sẽ build real-time multiplayer Tic-Tac-Toe game dùng Node.js, Socket.IO, và Redis. Game cho phép hai players connect từ different browser tabs, take turns playing, và see real-time updates khi chơi. Chúng ta dùng Redis manage game state synchronization across multiple WebSocket servers, làm application scalable.
Cuối cùng, bạn sẽ có fully functional game với real-time capabilities và solid understanding cách dùng WebSockets và Redis build scalable real-time applications.
What You Will Learn
Cách dùng Socket.IO cho real-time communication.
Cách dùng Redis Pub/Sub synchronize game state across multiple clients.
Cách setup scalable WebSocket server architecture.
Prerequisites
Trước khi bắt đầu, ensure bạn có installed:
Node.js (v16 hoặc cao hơn)
Redis
Docker (optional, cho run Redis in container)
Basic knowledge JavaScript, Node.js, và WebSockets.
Mục lục
Project Overview
Step 1: Setting Up Your Development Environment
Step 2: Setting Up the Project
Step 3: Implementing the WebSocket Server with Redis
Step 4: Implement the React Frontend interface
Step 5: Running the Application
Step 6: Viewing Redis Messages in Real-Time
Demo
Conclusion
Project Overview
Chúng ta build real-time Tic-Tac-Toe game với features:
Hai players connect và play game.
Game board updates real-time across different browser tabs.
Game announce winner hoặc declare draw khi board full.
Chúng ta dùng:
Node.js với Socket.IO handle WebSocket connections.
Redis Pub/Sub manage game state synchronization across clients.
Step 1: Setting Up Your Development Environment
Installing Node.js
Ensure Node.js installed:
node -v
Nếu chưa có, download từ Node.js.
Installing Redis
Install Redis locally hoặc run Docker container.
macOS (Using Homebrew)
Đảm bảo Homebrew installed trước khi chạy commands:
brew install redis
brew services start redis
Verify Redis container running:
redis-cli ping
Bạn thấy:
PONG
Using Docker to Run Redis
docker run --name redis-server -p 6379:6379 -d redis
Check Redis running:
docker exec -it redis-server redis-cli ping
Step 2: Setting Up the Project
1. Create the Project Directory
mkdir tic-tac-toe
cd tic-tac-toe
npm init -y
2. Install Dependencies
npm install express socket.io redis dotenv
3. Create Environment Variables
Tạo file .env ở project root với contents:
PORT=3000
REDIS_HOST=localhost
REDIS_PORT=6379
Step 3: Implementing the WebSocket Server with Redis
Trong step này, setup WebSocket server handle real-time game interactions dùng Node.js, Socket.IO, và Redis. Server manage game state, handle player moves, ensure synchronization across multiple clients dùng Redis Pub/Sub.
Chúng ta break down mỗi section code để bạn hiểu exactly everything fits together.Server Code Explanation
Tạo file server.js thêm code sau:
import dotenv from 'dotenv';
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
import { createClient } from 'redis';
dotenv.config(); // Load environment variables from .env file
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "https://localhost:5173",
methods: ["GET", "POST"],
}
});
dotenv: Load env variables từ
.envfile giữ sensitive info như ports và keys secure.express: Setup basic Express server handle HTTP requests.
http: Tạo HTTP server dùng Node's built-in
httpmodule, dùng với Socket.IO cho WebSocket communication.Socket.IO: Library enable real-time, bidirectional communication giữa server và clients.
CORS Configuration: Allow cross-origin requests từ frontend chạy trên
localhost:5173.
Tiếp, tạo Redis publisher và subscriber clients, thêm code vào server.js:
// Initialize Redis clients
const pubClient = createClient();
const subClient = createClient();
await pubClient.connect();
await subClient.connect();
Dùng Redis handle real-time data synchronization giữa connected clients.
pubClient: Publish messages (như game state updates).
subClient: Subscribe messages (listen updates).
- connect(): Establish connection đến Redis server.
Trong paradigm này, một client publish updates, client kia subscribe updates. Giúp avoid blocking behavior, vì Redis clients ở subscribe mode chỉ receive messages.
Để subscribe Redis channels cho game updates, thêm code vào server.js:
// Subscribe to Redis channel for game updates
await subClient.subscribe('game-moves', (message) => {
gameState = JSON.parse(message);
io.emit('gameState', gameState);
});
subClient.subscribe: Listen messages trên channel
game-moves.Khi player mới make move, game state updated trong Redis, và all connected clients informed new state.
Parameter
messagechứa game state as string. Parse thành JavaScript object và broadcast updated state dùng Socket.IO.
Tiếp, define game state và functions, thêm code vào server.js:
// Define initial game state
let gameState = {
board: Array(9).fill(null),
xIsNext: true,
};
// Function to reset the game
function resetGame() {
gameState = {
board: Array(9).fill(null),
xIsNext: true,
};
}
gameState: Track current state của board và whose turn (
xIsNext).- Board represented as array 9 cells (mỗi cell 'X', 'O', hoặc
null). - Flag
xIsNextdetermine player's turn.
- Board represented as array 9 cells (mỗi cell 'X', 'O', hoặc
resetGame(): Reset board và turn indicator về initial state, cho phép new game start.
Tiếp, handle WebSocket connections, thêm code vào server.js:
io.on('connection', (socket) => {
console.log('New client connected:', socket.id);
// Send current game state to newly connected client
socket.emit('gameState', gameState);
io.on('connection')event triggered khi new client connects.socket.id: Unique identifier cho each connected client.
Gửi ngay
gameStatecho new client để họ thấy current board.
Handle player moves, thêm code vào server.js:
// Handle player moves
socket.on('makeMove', (index) => {
// Prevent move if cell already taken or game over
if (gameState.board[index] || calculateWinner(gameState.board)) return;
// Update board and switch turns
gameState.board[index] = gameState.xIsNext ? 'X' : 'O';
gameState.xIsNext = !gameState.xIsNext;
// Publish updated game state to Redis
pubClient.publish('game-moves', JSON.stringify(gameState));
io.emit('gameState', gameState);
});
makeMove: Event triggered khi player click cell.
Validation: Check cell occupied hoặc game ended trước make move.
Updating Game State: Nếu move valid, update board và switch turns.
Updated game state thì:
Published to Redis: Ensure all server instances stay in sync.
Broadcasted to all clients: Immediately update game board cho all players.
Handle game restarts, thêm code vào server.js:
// Handle game restarts
socket.on('restartGame', () => {
resetGame();
io.emit('gameState', gameState);
});
Handle client disconnection, thêm code vào server.js:
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
Cuối, process game logic, thêm functions vào server.js:
// Function to check if there's a winner
function calculateWinner(board) {
const lines = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
];
for (let [a, b, c] of lines) {
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
return board[a];
}
}
return null;
}
function isBoardFull(board) {
return board.every((cell) => cell !== null);
}
calculateWinner(): Check winning combination trên board.
isBoardFull(): Check all cells filled, indicate draw.
Step 4: Implement the React Frontend interface
Trong step này, build simple interactive React frontend cho Tic-Tac-Toe game. Frontend cho phép players connect WebSocket server, make moves, see game board update real-time.
Trong App.jsx, thêm code:
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
const socket = io('https://localhost:3000');
function App() {
const [gameState, setGameState] = useState({
board: Array(9).fill(null),
xIsNext: true,
winner: null
});
useEffect(() => {
socket.on('gameState', (state) => {
setGameState(state);
});
return () => socket.off('gameState');
}, []);
const handleClick = (index) => {
if (gameState.board[index] || gameState.winner) return;
socket.emit('makeMove', index);
};
const renderCell = (index) => (
);
return (
Multiplayer Tic-Tac-Toe
{[...Array(9)].map((_, i) => renderCell(i))}
);
}
export default App;
Tóm tắt React app breakdown:
WebSocket Connection:
- Frontend establish connection đến server dùng
socket.io-client.
- Frontend establish connection đến server dùng
State Management:
Game state (
gameState) managed với React'suseStatebao gồm:Board (9 cells).
Flag xIsNext indicate current player's turn.
Winner status.
Real-Time Updates:
useEffecthook:- Listen
gameStateupdates từ server. - Update local game state khi detect changes.
- Cleanup WebSocket listener khi component unmount.
- Listen
Handling Player Moves:
handleClickfunction:- Check cell occupied hoặc game has winner trước allow move.
- Gửi
makeMoveevent đến server với clicked cell index.
Game Board Rendering:
renderCellfunction tạo button cho each cell trên board.Board displayed dùng 3x3 grid.
Restart Game:
- "Restart Game" button emit
restartGameevent reset game board cho all players.
- "Restart Game" button emit
User Interface:
- Simple interactive layout cho players take turns và see updates real-time.
Step 5: Running the Application
Starting the Backend
Start backend server, mở terminal mới chạy:
cd tic-tac-toe
npm start
Starting the Frontend
Start React frontend server, mở terminal mới chạy commands (không dùng terminal backend vì cần cả hai chạy simultaneously):
cd tic-tac-toe-client
npm run dev
Accessing the Game
Mở browser navigate to:
https://localhost:5173
Step 6: Viewing Redis Messages in Real-Time
Khi game running, bạn view Redis messages xem real-time game state updates.
Mở terminal chạy:
redis-cli SUBSCRIBE game-moves
Hiển thị game updates:
1) "message"
2) "game-moves"
3) "{\"board\":[\"X\",null,\"O\",null,\"X\",null,null,null,null],\"xIsNext\":false}"
Mỗi lần move made hoặc game state changes, server publish updated game state đến channel game-moves. Dùng redis-cli, monitor updates real-time, as game being played.
Demo
Trong demo, bạn thấy Tic Tac Toe game chạy locally, demonstrate real-time updates khi players take turns.
Gameplay showcase features như turn switching, board updates, game state announcements (winner hoặc draw). Highlight game leverage WebSocket communication cung cấp smooth, interactive experience.
Kết luận
Chúc mừng, bạn successfully built real-time multiplayer Tic-Tac-Toe game dùng Node.js, Socket.IO, và Redis. Đây là những gì bạn học:
Real-time WebSocket communication dùng Socket.IO.
Game state management dùng Redis Pub/Sub.
Building responsive front-end với React.
Next Steps
Add player authentication.
Implement chat feature.
Deploy application to cloud provider cho scalability.
Happy coding!
Học code miễn phí. Chương trình open source freeCodeCamp đã giúp hơn 40.000 người có việc developer. Bắt đầu ngay