class PrinterWebSocket {
? constructor(url) {
? ? if (PrinterWebSocket.instance) {
? ? ? return PrinterWebSocket.instance;
? ? }
? ??
? ? this.url = url;
? ? this.socket = null;
? ? this.queue = []; // 打印任務隊列
? ? this.isConnecting = false;
? ? this.retryCount = 0;
? ? this.maxRetry = 3;
? ??
? ? PrinterWebSocket.instance = this;
? ? this.connect();
? }? connect() {
? ? if (this.isConnecting || this.socket) return;
? ??
? ? this.isConnecting = true;
? ? this.socket = new WebSocket(this.url);
? ??
? ? this.socket.onopen = () => {
? ? ? console.log('WebSocket連接已建立');
? ? ? this.isConnecting = false;
? ? ? this.retryCount = 0;
? ? ? this.processQueue();
? ? };
? ??
? ? this.socket.onmessage = (event) => {
? ? ? console.log('收到打印響應:', event.data);
? ? ? // 處理打印響應
? ? };
? ??
? ? this.socket.onclose = () => {
? ? ? console.log('WebSocket連接關閉');
? ? ? this.socket = null;
? ? ? if (this.retryCount < this.maxRetry) {
? ? ? ? this.retryCount++;
? ? ? ? setTimeout(() => this.connect(), 1000 * this.retryCount);
? ? ? }
? ? };
? ??
? ? this.socket.onerror = (error) => {
? ? ? console.error('WebSocket錯誤:', error);
? ? ? this.socket = null;
? ? ? this.isConnecting = false;
? ? };
? }? print(data) {
? ? if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
? ? ? console.log('連接未就緒,加入打印隊列');
? ? ? this.queue.push(data);
? ? ? if (!this.isConnecting) {
? ? ? ? this.connect();
? ? ? }
? ? ? return;
? ? }
? ??
? ? try {
? ? ? this.socket.send(JSON.stringify(data));
? ? ? console.log('打印指令已發送');
? ? } catch (error) {
? ? ? console.error('發送打印指令失敗:', error);
? ? ? this.queue.push(data);
? ? ? this.socket = null;
? ? ? this.connect();
? ? }
? }? processQueue() {
? ? while (this.queue.length > 0 && this.socket?.readyState === WebSocket.OPEN) {
? ? ? const data = this.queue.shift();
? ? ? this.socket.send(JSON.stringify(data));
? ? }
? }? static getInstance(url) {
? ? if (!PrinterWebSocket.instance) {
? ? ? PrinterWebSocket.instance = new PrinterWebSocket(url);
? ? }
? ? return PrinterWebSocket.instance;
? }
}
使用方法:
// 初始化單例(通常在應用啟動時)
const printer = PrinterWebSocket.getInstance('ws://your-print-server/ws');// 打印時直接使用
function handlePrint() {
? const printData = {
? ? type: 'print',
? ? content: '要打印的內容',
? ? copies: 1
? };
??
? printer.print(printData);
}// 頁面按鈕點擊事件
document.getElementById('print-btn').addEventListener('click', handlePrint);
?
優化建議
-
心跳機制:添加心跳保持連接活躍
// 在構造函數中添加 this.heartbeatInterval = setInterval(() => {if (this.socket?.readyState === WebSocket.OPEN) {this.socket.send(JSON.stringify({ type: 'heartbeat' }));} }, 30000);
-
連接狀態通知:提供連接狀態變更回調
// 添加狀態監聽 this.onStatusChange = null;// 狀態變更時 const notifyStatus = (status) => {if (this.onStatusChange) {this.onStatusChange(status);} };// 在onopen/onclose/onerror中調用notifyStatus
-
打印結果回調:支持打印結果返回
print(data, callback) {const task = { data, callback };this.queue.push(task);// ...其余邏輯 }// 在onmessage中處理響應時調用callback
這種實現方式避免了每次打印都創建新連接,提高了效率并減少了服務器壓力,同時保證了打印任務的可靠性。