优化 WebSocket 实现单例连接用于打印【待测试 】

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);

优化建议

  1. 心跳机制:添加心跳保持连接活跃
复制代码
// 在构造函数中添加
this.heartbeatInterval = setInterval(() => {
  if (this.socket?.readyState === WebSocket.OPEN) {
    this.socket.send(JSON.stringify({ type: 'heartbeat' }));
  }
}, 30000);
  1. 连接状态通知:提供连接状态变更回调
复制代码
// 添加状态监听
this.onStatusChange = null;

// 状态变更时
const notifyStatus = (status) => {
  if (this.onStatusChange) {
    this.onStatusChange(status);
  }
};

// 在onopen/onclose/onerror中调用notifyStatus
  1. 打印结果回调:支持打印结果返回
复制代码
print(data, callback) {
  const task = { data, callback };
  this.queue.push(task);
  // ...其余逻辑
}

// 在onmessage中处理响应时调用callback

这种实现方式避免了每次打印都创建新连接,提高了效率并减少了服务器压力,同时保证了打印任务的可靠性。

相关推荐
清 晨4 小时前
剖析 Web3 与传统网络模型的安全框架
网络·安全·web3·facebook·tiktok·instagram·clonbrowser
国科安芯4 小时前
抗辐照芯片在低轨卫星星座CAN总线通讯及供电系统的应用探讨
运维·网络·人工智能·单片机·自动化
gx23485 小时前
HCLP--MGER综合实验
运维·服务器·网络
VB5945 小时前
[N1盒子] 斐讯盒子N1 T1通用刷机包(可救砖)
网络
-XWB-5 小时前
【安全漏洞】防范未然:如何有效关闭不必要的HTTP请求方法,保护你的Web应用
服务器·网络·http
画中鸦6 小时前
VRRP的概念及应用场景
网络
MQ_SOFTWARE6 小时前
文件权限标记机制在知识安全共享中的应用实践
大数据·网络
一个网络学徒6 小时前
MGRE综合实验
运维·服务器·网络
拾光拾趣录6 小时前
GET/POST 的区别:从“为什么登录请求不能用 GET”说起
前端·网络协议
白鹭7 小时前
基于LNMP架构的分布式个人博客搭建
linux·运维·服务器·网络·分布式·apache