优化 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

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

相关推荐
游戏开发爱好者81 小时前
iOS重构期调试实战:架构升级中的性能与数据保障策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp
却道天凉_好个秋4 小时前
音视频学习(三十六):websocket协议总结
websocket·音视频
(:满天星:)5 小时前
第31篇:块设备与字符设备管理深度解析(基于OpenEuler 24.03)
linux·运维·服务器·网络·centos
野蛮人6号6 小时前
虚拟机网络编译器还原默认设置后VMnet8和VMnet1消失了
网络·vmware·虚拟机网络编译器·vmnet8消失
scuter_yu7 小时前
主流零信任安全产品深度介绍
运维·网络·安全
江苏思维驱动智能研究院有限公司7 小时前
Sophos 网络安全:全球领先的自适应安全解决方案提供商
网络·安全·web安全
面朝大海,春不暖,花不开7 小时前
Java网络编程:TCP/UDP套接字通信详解
java·网络·tcp/ip
ChicagoTypewriter7 小时前
计算机网络中的常用表项梳理
网络·计算机网络·智能路由器
DemonAvenger8 小时前
高性能 TCP 服务器的 Go 语言实现技巧:从原理到实践
网络协议·架构·go
Bruce_Liuxiaowei10 小时前
常见高危端口风险分析与防护指南
网络·网络安全·端口·信息搜集