在項目中使用WebSocket實現實時通信
WebSocket提供了一種在客戶端和服務器之間建立持久連接的方式,可以實現實時數據交換。下面我將展示如何在前端項目中集成WebSocket功能。
設計思路
我將創建一個簡單的聊天室界面來演示WebSocket的使用,包含以下功能:
- 建立WebSocket連接
- 發送和接收消息
- 顯示連接狀態
- 錯誤處理和重連機制
實現代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebSocket 聊天室</title><style>* {box-sizing: border-box;margin: 0;padding: 0;}body {font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;line-height: 1.6;color: #333;background-color: #f5f7fa;padding: 20px;}.container {max-width: 800px;margin: 0 auto;background: white;border-radius: 10px;box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);overflow: hidden;}header {background: #4a6ee0;color: white;padding: 20px;text-align: center;}.status-bar {display: flex;justify-content: space-between;align-items: center;padding: 10px 20px;background: #f0f4ff;border-bottom: 1px solid #e0e6ff;}.status {display: flex;align-items: center;}.status-indicator {width: 10px;height: 10px;border-radius: 50%;margin-right: 8px;}.connected {background: #4caf50;}.disconnected {background: #f44336;}.chat-container {padding: 20px;height: 400px;overflow-y: auto;background: #fafbff;}.message {margin-bottom: 15px;padding: 10px 15px;border-radius: 18px;max-width: 80%;word-break: break-word;}.received {background: #e6eeff;border-top-left-radius: 4px;align-self: flex-start;}.sent {background: #4a6ee0;color: white;border-top-right-radius: 4px;margin-left: auto;}.message-input {display: flex;padding: 15px;border-top: 1px solid #e0e6ff;background: #fafbff;}input {flex: 1;padding: 12px 15px;border: 1px solid #d0d9ff;border-radius: 20px;outline: none;font-size: 16px;}button {background: #4a6ee0;color: white;border: none;border-radius: 20px;padding: 12px 20px;margin-left: 10px;cursor: pointer;font-weight: bold;transition: background 0.3s;}button:hover {background: #3a5ec0;}button:disabled {background: #cccccc;cursor: not-allowed;}</style>
</head>
<body><div class="container"><header><h1>WebSocket 聊天室</h1></header><div class="status-bar"><div class="status"><div class="status-indicator disconnected" id="statusIndicator"></div><span id="statusText">未連接</span></div><button id="connectButton">連接</button></div><div class="chat-container" id="chatContainer"><div class="message received">歡迎使用聊天室!請點擊"連接"按鈕開始。</div></div><div class="message-input"><input type="text" id="messageInput" placeholder="輸入消息..." disabled><button id="sendButton" disabled>發送</button></div></div><script>document.addEventListener('DOMContentLoaded', function() {const statusIndicator = document.getElementById('statusIndicator');const statusText = document.getElementById('statusText');const connectButton = document.getElementById('connectButton');const chatContainer = document.getElementById('chatContainer');const messageInput = document.getElementById('messageInput');const sendButton = document.getElementById('sendButton');let websocket = null;const serverUrl = 'wss://echo.websocket.org'; // 這是一個公共的WebSocket測試服務器// 更新連接狀態UIfunction updateConnectionStatus(connected) {if (connected) {statusIndicator.className = 'status-indicator connected';statusText.textContent = '已連接';connectButton.textContent = '斷開';messageInput.disabled = false;sendButton.disabled = false;} else {statusIndicator.className = 'status-indicator disconnected';statusText.textContent = '未連接';connectButton.textContent = '連接';messageInput.disabled = true;sendButton.disabled = true;}}// 添加消息到聊天窗口function addMessage(content, isSent = false) {const messageElement = document.createElement('div');messageElement.className = `message ${isSent ? 'sent' : 'received'}`;messageElement.textContent = content;chatContainer.appendChild(messageElement);// 滾動到底部chatContainer.scrollTop = chatContainer.scrollHeight;}// 建立WebSocket連接function connect() {try {websocket = new WebSocket(serverUrl);websocket.onopen = function(event) {updateConnectionStatus(true);addMessage('已連接到服務器');};websocket.onmessage = function(event) {addMessage(event.data);};websocket.onclose = function(event) {updateConnectionStatus(false);addMessage('連接已關閉');websocket = null;};websocket.onerror = function(error) {console.error('WebSocket錯誤:', error);addMessage('發生錯誤,連接已斷開');updateConnectionStatus(false);};} catch (error) {console.error('無法建立連接:', error);addMessage('無法連接到服務器: ' + error.message);updateConnectionStatus(false);}}// 關閉WebSocket連接function disconnect() {if (websocket) {websocket.close();}}// 發送消息function sendMessage() {const message = messageInput.value.trim();if (message && websocket && websocket.readyState === WebSocket.OPEN) {websocket.send(message);addMessage(message, true);messageInput.value = '';}}// 連接/斷開按鈕點擊事件connectButton.addEventListener('click', function() {if (websocket && websocket.readyState === WebSocket.OPEN) {disconnect();} else {connect();}});// 發送按鈕點擊事件sendButton.addEventListener('click', sendMessage);// 按Enter鍵發送消息messageInput.addEventListener('keypress', function(event) {if (event.key === 'Enter') {sendMessage();}});});</script>
</body>
</html>
使用說明
- 頁面加載后,點擊"連接"按鈕建立WebSocket連接
- 連接成功后,可以在輸入框中輸入消息并點擊"發送"或按Enter鍵
- 發送的消息會顯示在右側(藍色),接收的消息顯示在左側(淺藍色)
- 可以隨時點擊"斷開"按鈕結束連接
實際項目中的注意事項
- 生產環境URL:示例中使用的是測試服務器,實際項目中應替換為您的WebSocket服務器地址
- 安全連接:生產環境應使用
wss://
(WebSocket Secure)而不是ws://
- 錯誤處理:需要根據實際需求完善錯誤處理和重連機制
- 身份驗證:實際應用中通常需要在建立連接時進行身份驗證
- 數據格式:通常使用JSON格式進行復雜數據交換
擴展功能
在實際項目中,您可能需要添加:
- 心跳機制保持連接活躍
- 消息重發機制確保消息送達
- 連接狀態監控和自動重連
- 支持不同的消息類型(文本、圖片、文件等)
- 用戶身份標識和會話管理