socket.io-client 連線、收發事件。mkdir chat-app && cd chat-app
npm init -y
npm install express socket.io
# 開發用 nodemon
npm install -D nodemon
server.jsconst express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// 靜態資源
app.use(express.static(path.join(__dirname, 'public')));
// Socket 連線處理
io.on('connection', socket => {
console.log('用戶連線:', socket.id);
// 進入大廳(可擴充房間機制)
socket.join('lobby');
// 接收公開訊息
socket.on('chat message', (msg, ack) => {
// 廣播給大廳其他人
socket.to('lobby').emit('chat message', {
id: socket.id,
text: msg,
time: new Date().toISOString()
});
ack?.({ status: 'ok' }); // 可選回調確認
});
// 斷線處理
socket.on('disconnect', reason => {
console.log('用戶斷線:', socket.id, reason);
socket.to('lobby').emit('system message', `${socket.id} 離開了聊天室`);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on https://localhost:${PORT}`));
public/index.html<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Socket.io 聊天室</title>
<style>
#messages { height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
.msg { margin: 4px 0; }
.msg .meta { color: #666; font-size: 0.85em; }
.msg.system { color: #e67e22; font-style: italic; }
#sendForm { display: flex; gap: 8px; }
#input { flex: 1; padding: 8px; }
</style>
</head>
<body>
<h2>即時聊天室</h2>
<div id="messages"></div>
<form id="sendForm">
<input id="input" placeholder="輸入訊息..." autocomplete="off" required />
<button type="submit">發送</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const $msg = document.getElementById('messages');
const $form = document.getElementById('sendForm');
const $input = document.getElementById('input');
socket.on('chat message', data => appendMsg(data.text, data.time, false));
socket.on('system message', text => appendMsg(text, null, true));
function appendMsg(text, time, isSystem) {
const div = document.createElement('div');
div.className = 'msg' + (isSystem ? ' system' : '');
div.innerHTML = (isSystem ? '' : ` `) + escapeHtml(text);
$msg.appendChild(div);
$msg.scrollTop = $msg.scrollHeight;
}
function escapeHtml(str) {
return str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
$form.addEventListener('submit', e => {
e.preventDefault();
const text = $input.value.trim();
if (!text) return;
socket.emit('chat message', text, resp => { console.log('Server ack:', resp); });
$input.value = '';
});
</script>
</body>
</html>
# package.json scripts
"scripts": { "start": "node server.js", "dev": "nodemon server.js" }
npm run dev
# 開啟兩個瀏覽器視窗 https://localhost:3000 測試
socket.join(roomId)、socket.to(roomId).emit(...)、io.in(roomId).emit(...)。io.use((socket, next) => { verify(socket.handshake.auth.token) })。socket.io-redis Adapter 共享狀態。npm i -D typescript @types/node @types/socket.io 獲得完整型別支援。Socket.io 讓即時通訊變得極簡:伺服端 io.on('connection')、前端 socket.emit/on,配合 Express 靜態服務,幾分鐘即可跑起功能完整的聊天室。生產環境再加上認證、持久化、集群適配器即可上線。