// 初始化WebSocket連接 const initWebSocket = () => {console.log("初始化鏈接中...")const websocketUrl =`ws://61.54.84.16:9090/`;// WebSocket服務器地址websocket = new WebSocket(websocketUrl)//使用真實的webscket// websocket = new MockWebSocket(websocketUrl);// 使用模擬的WebSocket文件websocket.onopen = () => {console.log('WebSocket連接已建立', websocket)// 發送心跳消息保持連接setInterval(() => {if (websocket.readyState === 1) {websocket.send(JSON.stringify({type: 'ping'}));}}, 30000);}websocket.onmessage = (event) => {try {console.log('接收到WebSocket數據:', event)const data = JSON.parse(event.data)handleWebSocketData(data)} catch (error) {console.error('解析WebSocket數據失敗:', error)}}websocket.onclose = () => {console.log('WebSocket連接已關閉')// 5秒后嘗試重連setTimeout(initWebSocket, 5000)}websocket.onerror = (error) => {console.error('WebSocket連接錯誤:', error)} }// 處理WebSocket接收到的數據 const handleWebSocketData = (msg) => {console.log('處理WebSocket數據:', msg) }
模擬webscket傳輸數據的過程
mockWebScoket.ts
// 模擬WebSocket對象(用于演示,實際項目中應連接真實服務器) // 其他頁面引入 // import MockWebSocket from './mockWebScoket'; // 調用 // const ws = new MockWebSocket('ws://example.com/ws'); // mock返回的數據 // currentNumber:"A015" // department:"婦科診區" // waitingQueue: ['A016', 'A017', 'A018', 'A019', 'A020', 'A021', 'A022', 'A023', 'A024', 'A025']export class MockWebSocket {static CONNECTING = 0;static OPEN = 1;static CLOSED = 3;static DEPARTMENTS = ["內科診區", "外科診區", "兒科診區", "婦科診區", "眼科診區"];constructor(url) {this.url = url;this.readyState = MockWebSocket.CONNECTING;this.onopen = null;this.onmessage = null;this.onclose = null;this.onerror = null;this.mockInterval = null;//默認觸發// 模擬連接過程setTimeout(() => {// 模擬連接成功this.readyState = MockWebSocket.OPEN;if (this.onopen) {this.onopen(new Event('open'));}// 開始發送模擬數據this.startMockData();}, 500);}send(data) {if (this.readyState !== MockWebSocket.OPEN) {console.warn("WebSocket is not open. Current state:", this.readyState);return;}console.log('發送數據:', data);}close() {this.readyState = MockWebSocket.CLOSED;if (this.onclose) {this.onclose(new CloseEvent('close'));}if (this.mockInterval) {clearInterval(this.mockInterval);this.mockInterval = null;}}startMockData() {console.log("進入mock的數據")if (this.mockInterval) {clearInterval(this.mockInterval);}let counter = 0;const department = MockWebSocket.DEPARTMENTS[Math.floor(Math.random() * MockWebSocket.DEPARTMENTS.length)];this.mockInterval = setInterval(() => {counter = (counter % 50) + 1;const currentNumber = `A${counter.toString().padStart(3, '0')}`;const waitingQueue = [];for (let i = 1; i <= 10; i++) {const nextNum = (counter + i) <= 50? counter + i: (counter + i) % 50 || 50;waitingQueue.push(`A${nextNum.toString().padStart(3, '0')}`);}//這是傳輸過去的數據const data = {currentNumber:currentNumber,department: department,waitingQueue: waitingQueue};if (this.onmessage) {this.onmessage({data: JSON.stringify(data)});}}, 15000);} }