最新workerman 聊天室更新

Brave Ye
系統管理員
Posts: 6294
Joined: 2025-11-08, 05:32
Location: Taiwan

最新workerman 聊天室更新

Post by Brave Ye »

更新重點
chat.js 改為 http:// ip 與 https:// 網址 連入可以互相看到上傳早安圖
之前是 http:// 上傳圖片 與 https:// 上傳圖片 互相看不到

更改 start.php 在線人員邏輯 避免切換頻道時 看不到目前所在頻道的在線人員

更改 upload.php 讓 上傳圖檔 沒有偽裝圖檔的惡意程式

安裝php8.5 event擴展及啟用
viewtopic.php?t=5735

在debian 13.7 安裝 composer
https://getcomposer.org/download/


# 啟動並設定 Nginx
sudo systemctl enable nginx --now


# 重啟 PHP-FPM 確保它正確載入剛安裝的 Redis 模組
sudo systemctl restart php8.5-fpm
sudo systemctl enable php8.5-fpm

cd /var/www/my-chat
composer require workerman/gateway-worker

在 Workerman / GatewayWorker 架構配合 MariaDB 的環境下,最標準且優雅的實作方式是利用後端的 onClose 斷線回呼機制。當使用者關閉瀏覽器分頁、關閉整個瀏覽器、甚至手機突然沒電斷網時,GatewayWorker 會即時偵測到連線中斷,並自動觸發 Events::onClose($client_id),您只要在這裡面撰寫刪除資料庫資料的 SQL 即可。
以下是完整的實作流程與程式碼範例:


MariaDB 資料庫設計 (以儲存臨時在線用戶為例)

在您的資料庫中建立一張儲存當前聊天室活躍用戶的資料表(例如 online_users),裡面必須包含 client_id 作為刪除的依據。
CREATE TABLE `online_users` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`client_id` VARCHAR(32) NOT NULL,
`user_name` VARCHAR(50) NOT NULL,
`ip_address` VARCHAR(45) NOT NULL,
`joined_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY `idx_client` (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
nano /etc/systemd/system/workerman.service
[Unit]
Description=Workerman Gateway Chat Service
After=network.target mariadb.service redis-server.service
Requires=mariadb.service redis-server.service

[Service]
Type=forking
User=root
Group=root
# 關鍵設定:直接針對此服務提高檔案描述符 (連線數) 上限
LimitNOFILE=65535
WorkingDirectory=/var/www/my-chat
PIDFile=/var/www/my-chat/workerman.start.php.pid
ExecStart=/usr/bin/php start.php start -d
ExecReload=/usr/bin/php start.php reload
ExecStop=/usr/bin/php start.php stop
Restart=always
RestartSec=3
PrivateTmp=true

[Install]
WantedBy=multi-user.target


sudo nano /var/www/my-chat/public/index.html
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Zine-TW 聊天室 (行動省電版)</title>
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100dvh; background-color: #000; color: #e0e0e0; font-family: sans-serif; overflow: hidden; display: flex; }
.sidebar { width: 250px; background-color: #121212; border-right: 1px solid #222; display: flex; flex-direction: column; padding: 10px; box-sizing: border-box; z-index: 999; }
.sidebar.hidden { display: none !important; }
.user-item { padding: 6px 8px; margin: 4px 0; background-color: #1a1a1a; border-radius: 4px; cursor: pointer; font-size: 14px; }
.chat-area { flex: 1; display: flex; flex-direction: column; height: 100%; background-color: #000; overflow: hidden; position: relative; }
.chat-header { padding: 10px 15px; background-color: #121212; border-bottom: 1px solid #222; font-size: 14px; display: flex; justify-content: space-between; align-items: center; }
.messages-container { flex: 1; padding: 15px; overflow-y: auto; -webkit-overflow-scrolling: touch; display: flex; flex-direction: column; gap: 10px; }
.msg-item { display: flex; flex-direction: column; margin-bottom: 2px; }
.msg-item.history { opacity: 0.85; }
.msg-meta { font-size: 12px; color: #777; margin-bottom: 3px; display: flex; align-items: center; gap: 6px; }
.msg-time { color: #555; }
.msg-content { background-color: #111; color: #e0e0e0; padding: 8px 12px; border-radius: 6px; max-width: 85%; width: fit-content; word-break: break-all; line-height: 1.4; border: 1px solid #222; }
.msg-item.system .msg-content { background: none; border: none; color: #d4af37; font-style: italic; font-size: 13px; padding: 0; }
.input-area { display: flex; align-items: center; padding: 10px 15px; background-color: #121212; border-top: 1px solid #222; gap: 10px; box-sizing: border-box; width: 100%; }
.upload-icon { background: none; border: none; font-size: 24px; cursor: pointer; padding: 0; display: flex; align-items: center; justify-content: center; }
.chat-input { flex: 1; height: 40px; background-color: #1e1e1e; border: 1px solid #333; border-radius: 6px; color: #fff; padding: 0 12px; font-size: 16px; box-sizing: border-box; outline: none; }
.send-btn { height: 40px; padding: 0 20px; background-color: #1f6feb; border: none; border-radius: 6px; color: #fff; font-size: 14px; font-weight: bold; cursor: pointer; white-space: nowrap; }
@media (max-width: 768px) { .sidebar { position: absolute; left: 0; top: 0; width: 80%; height: 100%; box-shadow: 5px 0 15px rgba(0,0,0,0.7); display: none; } .sidebar.active { display: flex !important; } .chat-header { font-size: 13px; padding: 10px; } }
</style>
</head>
<body>
<div class="sidebar" id="sidebar_menu">
<h3 style="display:flex; justify-content:space-between; align-items:center; margin-top:0;">
<span>☰ 頻道/成員</span>
<button class="send-btn" style="padding: 4px 10px; height:auto; font-size: 12px;" onclick="toggleSidebar()">收起</button>
</h3>
<p><strong>名字:</strong> <span id="my_name_display">載入中...</span> <button class="send-btn" style="padding: 2px 8px; height:auto; font-size: 12px;" onclick="changeName()">修改</button></p>
<h4> 群聊頻道</h4>
<div id="rooms_list">
<p id="room_大廳公聊" style="color: #1f6feb; font-weight: bold; cursor:pointer;" onclick="switchRoom('大廳公聊')"># 大廳公聊</p>
<p id="room_電玩動漫" style="cursor:pointer;" onclick="switchRoom('電玩動漫')"># 電玩動漫</p>
<p id="room_音樂分享" style="cursor:pointer;" onclick="switchRoom('音樂分享')"># 音樂分享</p>
<p id="room_閒聊八卦" style="cursor:pointer;" onclick="switchRoom('閒聊八卦')"># 閒聊八卦</p>
</div>
<h4> 在線成員 (點擊私訊)</h4>
<div id="user_list"><p style="color:#888; font-style:italic;">載入中...</p></div>
</div>
<div class="chat-area">
<div class="chat-header">
<div onclick="toggleSidebar()" style="cursor: pointer; background: #222; padding: 6px 10px; border-radius: 4px; font-weight: bold; font-size: 12px;">☰ 頻道/成員</div>
<div>當前頻道:<span id="current_room_title" style="color: #1f6feb; font-weight: bold;">大廳公聊</span></div>
<div>狀態:<span id="conn-status" style="color: #f39c12;">● 連線中...</span></div>
</div>
<div class="messages-container" id="message-box">
<div class="msg-item system"><div class="msg-content">可以開始聊天</div></div>
</div>
<div class="input-area">
<input type="file" id="img_file_input" accept="image/*" style="display: none;" onchange="handleImageUpload(this)">
<button class="upload-icon" onclick="document.getElementById('img_file_input').click()" title="上傳圖片">📸</button>
<input type="text" class="chat-input" id="msg_input" placeholder="輸入訊息... (點擊成員可啟用私訊)" autocomplete="off">
<button class="send-btn" id="send-btn" onclick="sendMsg()">發送</button>
</div>
</div>
<script src="chat.js"></script>
</body>
</html>
nano /var/www/my-chat/public/chat.js
// chat.js - 業務精簡優化版 (整合全域訊息防重複鎖、Redis歷史紀錄防錯、RWD氣泡、斷線暱稱維持)
const isHttps = window.location.protocol === 'https:';
const wsUrl = (isHttps ? 'wss://' : 'ws://') + window.location.host + '/wss';
const uploadApiUrl = '/chat/upload.php';

var ws, currentRoom = '大廳公聊', myName = '';
var reconnectDelay = 1000, maxReconnectDelay = 30000, isAlive = false, heartbeatInterval;

// 狀態鎖:防止重複觸發圖片上傳非同步請求
var isUploading = false;

// 【全域防重複鎖】用來記錄目前聊天室畫面上已經渲染過的唯一 msg_id
var renderedMsgIds = new Set();

const chatMessages = document.getElementById('message-box');
const messageInput = document.getElementById('msg_input');
const sendBtn = document.getElementById('send-btn');
const userListContainer = document.getElementById('user_list');
const currentRoomTitle = document.getElementById('current_room_title');
const statusDot = document.getElementById('conn-status');

function initWebSocket() {
updateStatusDisplay("連線中...", "#f39c12");
ws = new WebSocket(wsUrl);

ws.onopen = () => {
updateStatusDisplay("已連線", "#238636");
reconnectDelay = 1000;
messageInput.disabled = false;
if(sendBtn) sendBtn.disabled = false;
isAlive = true;

// 心跳機制:定時發送 ping 維持連線
heartbeatInterval = setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) {
if (!isAlive) { ws.close(); return; }
isAlive = false;
ws.send('__ping__');
}
}, 30000);
};

ws.onclose = () => {
updateStatusDisplay("斷線", "#e74c3c");
messageInput.disabled = true;
if(sendBtn) sendBtn.disabled = true;
clearInterval(heartbeatInterval);
setTimeout(() => {
reconnectDelay = Math.min(reconnectDelay * 2, maxReconnectDelay);
initWebSocket();
}, reconnectDelay);
};

ws.onerror = () => ws.close();

ws.onmessage = (e) => {
if (e.data === '__ping__') { isAlive = true; return; }
const data = JSON.parse(e.data);

if (data.type === 'init') {
// 斷線重連核心邏輯:檢查瀏覽器本地有沒有存過舊暱稱
const savedName = localStorage.getItem('chat_my_name');

if (savedName && savedName !== data.my_name) {
ws.send(JSON.stringify({ type: 'set_name', name: savedName }));
myName = savedName;
} else {
myName = data.my_name;
localStorage.setItem('chat_my_name', myName);
}

const nameDisplayEl = document.getElementById('my_name_display');
if (nameDisplayEl) nameDisplayEl.innerText = myName;

} else if (data.type === 'user_list_update') {
renderUsers(data.users);
} else if (data.type === 'chat' && data.room === currentRoom) {
appendMessage(data);
} else if (data.type === 'user_joined') {
if (data.user.startsWith('用戶_') && localStorage.getItem('chat_my_name') !== data.user && localStorage.getItem('chat_my_name')) {
return;
}
appendSystemMessage(`${data.user} 進入了聊天室`);
} else if (data.type === 'user_left') {
appendSystemMessage(`${data.user} 離開了聊天室`);
} else if (data.type === 'name_changed') {
if (data.from === myName || data.to === localStorage.getItem('chat_my_name')) {
myName = data.to;
const nameDisplayEl = document.getElementById('my_name_display');
if (nameDisplayEl) nameDisplayEl.innerText = myName;
if (data.from.startsWith('用戶_')) {
return;
}
}
appendSystemMessage(`${data.from} 已改名為 ${data.to}`);
}
};
}

function renderUsers(users) {
if (!users || !userListContainer) return;
userListContainer.innerHTML = '';
const currentRoomUsers = users.filter(u => u.rooms.includes(currentRoom));
if (currentRoomUsers.length === 0) {
userListContainer.innerHTML = '<div style="padding:10px;color:#555;font-style:italic;">暫無成員</div>';
return;
}
currentRoomUsers.forEach(user => {
const uDiv = document.createElement('div');
uDiv.className = 'user-item';
uDiv.innerText = ' ' + user.name + (user.name === myName ? " (你)" : "");
uDiv.onclick = () => { messageInput.value = '@' + user.name + ' '; messageInput.focus(); };
userListContainer.appendChild(uDiv);
});
}
function appendMessage(data) {
let txt = data.text;

// 【終極唯一的防重複鎖】直接識別後端發送過來的唯一 msg_id
if (data.msg_id) {
if (renderedMsgIds.has(data.msg_id)) return;
renderedMsgIds.add(data.msg_id);
} else {
const fallbackId = data.from_id + "_" + data.time + "_" + txt;
if (renderedMsgIds.has(fallbackId)) return;
renderedMsgIds.add(fallbackId);
}

const msgDiv = document.createElement('div');
msgDiv.className = 'msg-item';
if (data.is_history) msgDiv.classList.add('history');

// 1. 安全建立發話者與時間標頭(完全棄用 innerHTML,改用 textContent)
const displayTime = data.time ? data.time : new Date().toLocaleTimeString('zh-TW', { hour12: false });
const meta = document.createElement('div');
meta.className = 'msg-meta';

const userSpan = document.createElement('span');
userSpan.className = 'msg-user';
const strongEl = document.createElement('strong');
strongEl.textContent = data.from_id; // 即使暱稱含 <script> 也會變成純文字
userSpan.appendChild(strongEl);

const timeSpan = document.createElement('span');
timeSpan.className = 'msg-time';
timeSpan.textContent = `[${displayTime}]`;

meta.appendChild(userSpan);
meta.appendChild(timeSpan);
msgDiv.appendChild(meta);

// 2. 處理網址網域轉換(相容 IP 直連與主網域)
const curPrefix = window.location.protocol + '//' + window.location.host + '/chat/uploads/';
if (typeof txt === 'string' && txt.includes('/chat/uploads/')) {
txt = txt.replace(/^https?:\/\/(www\.)?zine-tw\.com\/chat\/uploads\//i, curPrefix)
.replace(/^http:\/\/123\.241\.40\.195\/chat\/uploads\//i, curPrefix);
}

const contentDiv = document.createElement('div');
contentDiv.className = 'msg-content';

// 3. 嚴格驗證圖片網址白名單(只允許本站 /chat/uploads/ 的安全圖片格式)
const safeImgRegex = /^(https?:\/\/[a-zA-Z0-9.-]+)?\/chat\/uploads\/[a-zA-Z0-9_.-]+\.(jpg|jpeg|png|gif|webp)$/i;

if (typeof txt === 'string' && safeImgRegex.test(txt.trim())) {
const cleanUrl = txt.trim();
const imgEl = document.createElement('img');
imgEl.src = cleanUrl; // 透過屬性賦值,不會有屬性注入風險
imgEl.style.cssText = "max-width:100%; max-height:250px; border-radius:6px; margin-top:5px; display:block; cursor:pointer;";
imgEl.onclick = () => window.open(cleanUrl, '_blank', 'noopener,noreferrer');
contentDiv.appendChild(imgEl);
} else {
// 一般文字訊息一律使用 textContent 安全輸出
contentDiv.textContent = txt;
}

msgDiv.appendChild(contentDiv);
chatMessages.appendChild(msgDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}

function appendSystemMessage(text) {
const row = document.createElement("div");
row.className = "msg-item system";

const content = document.createElement("div");
content.className = "msg-content";
content.textContent = text; // 防止改名廣播或進出通知夾帶 HTML 標籤

row.appendChild(content);
chatMessages.appendChild(row);
chatMessages.scrollTop = chatMessages.scrollHeight;
}


function sendMsg() {
const text = messageInput.value.trim();
if (text === '' || !ws || ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({ type: 'chat', room: currentRoom, text: text }));
messageInput.value = '';
messageInput.focus();
}

function switchRoom(roomName) {
if (roomName === currentRoom) return;
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'join_room', room: roomName }));
currentRoom = roomName;
currentRoomTitle.innerText = roomName;

['大廳公聊', '電玩動漫', '音樂分享', '閒聊八卦'].forEach(r => {
const el = document.getElementById('room_' + r);
if (el) { el.style.color = (r === roomName) ? '#1f6feb' : '#e0e0e0'; el.style.fontWeight = (r === roomName) ? 'bold' : 'normal'; }
});

// 切換房間時清空舊房的防重複快取
renderedMsgIds.clear();
chatMessages.innerHTML = '';
appendSystemMessage(`已切換至頻道:# ${currentRoom}`);
if (window.innerWidth <= 768) document.getElementById('sidebar_menu').classList.remove('active');
}

function handleImageUpload(inputElement) {
// 最嚴格的開頭防禦鎖
if (!inputElement || !inputElement.files || inputElement.files.length === 0 || isUploading) {
return;
}

isUploading = true;
const fileTarget = inputElement.files[0]; // 精確鎖定第一個檔案物件
inputElement.value = ''; // 在非同步發起前,立刻徹底清空 DOM 節點阻斷連擊

const formData = new FormData();
formData.append('image', fileTarget);

fetch(uploadApiUrl, { method: 'POST', body: formData })
.then(r => {
if (!r.ok) throw new Error('網路回應錯誤');
return r.json();
})
.then(data => {
if (data.success && data.url && ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'chat', room: currentRoom, text: data.url }));
} else {
alert('上傳失敗:' + (data.message || '未知錯誤'));
}
})
.catch((err) => {
console.error(err);
alert('連線伺服器失敗');
})
.finally(() => {
setTimeout(() => {
isUploading = false;
}, 800);
});
}

function changeName() {
const newName = prompt("請輸入您的新名字 (20 字以內):", myName);
if (!newName) return;
const trimmed = newName.trim();
if (trimmed && trimmed !== myName && ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'set_name', name: trimmed }));
myName = trimmed;

const nameDisplayEl = document.getElementById('my_name_display');
if (nameDisplayEl) nameDisplayEl.innerText = myName;
localStorage.setItem('chat_my_name', trimmed);
}
}

// 側邊欄切換
function toggleSidebar() {
const sidebar = document.getElementById('sidebar_menu');
if (!sidebar) return;
sidebar.classList.toggle(window.innerWidth <= 768 ? 'active' : 'hidden');
}

if (messageInput) {
messageInput.onkeydown = (e) => { if (e.keyCode === 13) sendMsg(); };
}

function updateStatusDisplay(text, color) {
if (statusDot) {
statusDot.innerText = `● ${text}`;
statusDot.style.color = color;
}
}

initWebSocket();
nano /var/www/my-chat/upload.php
<?php
// upload.php (安全強化版)
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['image'])) {
echo json_encode(['success' => false, 'message' => '無效的請求']);
exit;
}

$file = $_FILES['image'];

// 1. 檢查上傳過程是否有系統錯誤
if ($file['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['success' => false, 'message' => '檔案上傳發生錯誤 (代碼: ' . $file['error'] . ')']);
exit;
}

// 2. 限制檔案大小 (上限 5MB,可依需求調整)
$max_size = 5 * 1024 * 1024;
if ($file['size'] > $max_size) {
echo json_encode(['success' => false, 'message' => '圖片檔案過大,請勿超過 5MB']);
exit;
}

// 3. 檢查副檔名白名單
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array($ext, $allowed_ext)) {
echo json_encode(['success' => false, 'message' => '格式不符,僅支援 jpg, png, gif, webp']);
exit;
}

// 4. 【核心安全驗證】使用 getimagesize 檢查檔案二進位標頭,確保為真實圖片
$image_info = @getimagesize($file['tmp_name']);
$allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

if ($image_info === false || !in_array($image_info['mime'], $allowed_mimes)) {
echo json_encode(['success' => false, 'message' => '安全驗證失敗:檔案並非有效的圖片格式']);
exit;
}

// 5. 建立儲存資料夾 (權限設為 0755 較 0777 更安全)
$upload_dir = 'uploads/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}

// 6. 重新命名檔案防止重複與路徑穿越
$new_name = uniqid('chat_', true) . '.' . $ext;
$target = $upload_dir . $new_name;

// 7. 移動檔案並回傳完整的圖片 URL 網址
if (move_uploaded_file($file['tmp_name'], $target)) {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$file_url = $protocol . $_SERVER['HTTP_HOST'] . '/chat/' . $target;

echo json_encode(['success' => true, 'url' => $file_url]);
} else {
echo json_encode(['success' => false, 'message' => '檔案寫入伺服器失敗']);
}
nano /var/www/my-chat/start.php
<?php
// start.php
use Workerman\Worker;
use GatewayWorker\Gateway;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Register;
use GatewayWorker\Lib\Gateway as GatewayLib;

require_once __DIR__ . '/vendor/autoload.php';

$ROOMS = ['大廳公聊', '電玩動漫', '音樂分享', '閒聊八卦'];

$register = new Register('text://127.0.0.1:1238');

$gateway = new Gateway("websocket://127.0.0.1:8282");
$gateway->name = 'ChatGateway';
$gateway->count = 4;
$gateway->lanIp = '127.0.0.1';
$gateway->startPort = 2900;
$gateway->registerAddress = '127.0.0.1:1238';

$worker = new BusinessWorker();
$worker->name = 'ChatBusinessWorker';
$worker->count = 4;
$worker->registerAddress = '127.0.0.1:1238';
$worker->eventHandler = 'Events';

class Events {
protected static $redis;
protected static $db;
public static $isReloading = false;

public static function onWorkerStart($businessWorker) {
self::$redis = new \Redis();
self::$redis->connect('127.0.0.1', 6379);

$db_host = '127.0.0.1';
$db_name = 'workerman';
$db_user = 'workerman_user';
$db_pass = 'RqSiAd27';

try {
self::$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8mb4", $db_user, $db_pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => true
]);
} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage() . "\n";
}

// 僅在手動 start 時清空舊名單,凌晨 reload 時保留在線狀態
if ($businessWorker->id === 0 && self::$db && !self::$isReloading) {
try {
self::$db->exec("TRUNCATE TABLE online_users");
echo "【系統提示】MariaDB 在線用戶名單已成功初始化清空。\n";
} catch (PDOException $e) {
echo "清空舊名單失敗: " . $e->getMessage() . "\n";
}
}
}
public static function onWebSocketConnect($client_id, $data) {
global $ROOMS;
$user_name = '用戶_' . rand(100, 999);
$ip = $_SERVER['HTTP_X_REAL_IP'] ?? ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'));

if (self::$db) {
try {
$stmt = self::$db->prepare("INSERT INTO online_users (client_id, user_name, ip_address) VALUES (:client_id, :user_name, :ip)");
$stmt->execute([
':client_id' => $client_id,
':user_name' => $user_name,
':ip' => $ip
]);
} catch (PDOException $e) {
echo "Insert user failed: " . $e->getMessage() . "\n";
}
}

GatewayLib::setSession($client_id, ['user_name' => $user_name, 'rooms' => ['大廳公聊']]);
GatewayLib::joinGroup($client_id, '大廳公聊');
GatewayLib::sendToClient($client_id, json_encode(['type' => 'init', 'rooms' => $ROOMS, 'my_name' => $user_name]));

self::sendHistoryToClient($client_id, '大廳公聊');
GatewayLib::sendToGroup('大廳公聊', json_encode(['type' => 'user_joined', 'user' => $user_name]));
self::broadcastOnlineList();
}

public static function onMessage($client_id, $message) {
global $ROOMS;
if ($message === '__ping__') return;
$decoded = json_decode($message, true);
if (!$decoded) return;
$session = GatewayLib::getSession($client_id);
$myName = $session['user_name'];
$time = date('H:i:s');

switch ($decoded['type'] ?? '') {
case 'set_name':
$newName = trim($decoded['name'] ?? '');
if ($newName !== '' && mb_strlen($newName) <= 20) {
$oldName = $session['user_name'];
$session['user_name'] = $newName;
GatewayLib::setSession($client_id, $session);

if (self::$db) {
try {
$stmt = self::$db->prepare("UPDATE online_users SET user_name = :user_name WHERE client_id = :client_id");
$stmt->execute([':user_name' => $newName, ':client_id' => $client_id]);
} catch (PDOException $e) {}
}

GatewayLib::sendToGroup('大廳公聊', json_encode(['type' => 'name_changed', 'from' => $oldName, 'to' => $newName]));
self::broadcastOnlineList();
}
break;

case 'join_room':
$room = $decoded['room'] ?? '';
if (in_array($room, $ROOMS)) {
if (!in_array($room, $session['rooms'])) {
$session['rooms'][] = $room;
GatewayLib::setSession($client_id, $session);
GatewayLib::joinGroup($client_id, $room);
self::sendHistoryToClient($client_id, $room);
}
self::broadcastOnlineList();
}
break;

case 'chat':
$text = $decoded['text'] ?? '';
if (empty($text)) break;
$room = $decoded['room'] ?? '大廳公聊';
$msg_id = uniqid('msg_', true);

$msgPayload = [
'msg_id' => $msg_id,
'type' => 'chat',
'room' => $room,
'from_id' => $myName,
'text' => $text,
'time' => $time,
];
$jsonMsg = json_encode($msgPayload);

$redisKey = "chat:history:room:{$room}";
self::$redis->rPush($redisKey, $jsonMsg);
self::$redis->lTrim($redisKey, -500, -1);

GatewayLib::sendToGroup($room, $jsonMsg);
break;
}
}
public static function onClose($client_id) {
if (self::$db) {
try {
$stmt = self::$db->prepare("DELETE FROM online_users WHERE client_id = :client_id");
$stmt->execute([':client_id' => $client_id]);
} catch (PDOException $e) {}
}

$session = GatewayLib::getSession($client_id);
if (isset($session['user_name'])) {
GatewayLib::sendToGroup('大廳公聊', json_encode(['type' => 'user_left', 'user' => $session['user_name']]));
self::broadcastOnlineList();
}
}

// 精準抓取各頻道的即時在線成員並廣播給全站
private static function broadcastOnlineList() {
global $ROOMS;
$userMap = [];

foreach ($ROOMS as $room) {
$sessions = GatewayLib::getClientSessionsByGroup($room);
if (!empty($sessions)) {
foreach ($sessions as $cid => $sess) {
$uname = $sess['user_name'] ?? '未知用戶';
if (!isset($userMap[$cid])) {
$userMap[$cid] = [
'name' => $uname,
'rooms' => []
];
}
if (!in_array($room, $userMap[$cid]['rooms'])) {
$userMap[$cid]['rooms'][] = $room;
}
}
}
}

GatewayLib::sendToAll(json_encode([
'type' => 'user_list_update',
'users' => array_values($userMap)
]));
}

private static function sendHistoryToClient($client_id, $room) {
$redisKey = "chat:history:room:{$room}";
$history = self::$redis->lRange($redisKey, 0, -1);
if (!empty($history)) {
foreach ($history as $msgJson) {
$msgArray = json_decode($msgJson, true);
$msgArray['is_history'] = true;
GatewayLib::sendToClient($client_id, json_encode($msgArray));
}
}
}
}

// 監聽主進程 reload 事件,避免誤清空在線名單
Worker::$onMasterReload = function() {
Events::$isReloading = true;
};

Worker::runAll();
sudo pkill -f start.php
sudo lsof -i :8282
sudo systemctl daemon-reload
sudo systemctl enable workerman
sudo systemctl reload workerman

-------------------------------------------------------------------------------
查看聊天紀錄
sudo apt install -y redis-server php8.5-redis
# 啟動並設定 Redis
sudo systemctl enable redis-server --now
安裝Redis Insight for windows