From 2eeb37df8e6bff557f1b7c74cf747c7ded374d90 Mon Sep 17 00:00:00 2001 From: linfso Date: Sat, 11 May 2024 07:13:32 +0800 Subject: [PATCH] md --- src/utils/TnPrinterSdk.js | 110 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 src/utils/TnPrinterSdk.js diff --git a/src/utils/TnPrinterSdk.js b/src/utils/TnPrinterSdk.js new file mode 100644 index 00000000..924cc7dc --- /dev/null +++ b/src/utils/TnPrinterSdk.js @@ -0,0 +1,110 @@ +import { Message } from 'element-ui' +import { getToken } from '@/utils/auth' // 与后端的协商,websocket请求需要带上token参数 +let websock = null +let messageCallback = null +let errorCallback = null +let wsUrl = '' +let tryTime = 0 + +// 接收ws后端返回的数据 +function websocketonmessage (e) { + messageCallback(JSON.parse(e.data)) +} + +/** + * 发起websocket连接 + * @param {Object} agentData 需要向后台传递的参数数据 + */ +function websocketSend (agentData) { + // 加延迟是为了尽量让ws连接状态变为OPEN + setTimeout(() => { + // 添加状态判断,当为OPEN时,发送消息 + if (websock.readyState === websock.OPEN) { // websock.OPEN = 1 + // 发给后端的数据需要字符串化 + websock.send(JSON.stringify(agentData)) + } + if (websock.readyState === websock.CLOSED) { // websock.CLOSED = 3 + console.log('websock.readyState=3') + Message.error('ws连接异常,请稍候重试') + errorCallback() + } + }, 500) +} + +// 关闭ws连接 +function websocketclose (e) { + // e.code === 1000 表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。 + // e.code !== 1000 表示非正常关闭。 + if (e && e.code !== 1000) { + Message.error('ws连接异常,请稍候重试') + errorCallback() + // // 如果需要设置异常重连则可替换为下面的代码,自行进行测试 + // if (tryTime < 10) { + // setTimeout(function() { + // websock = null + // tryTime++ + // initWebSocket() + // console.log(`第${tryTime}次重连`) + // }, 3 * 1000) + //} else { + // Message.error('重连失败!请稍后重试') + //} + } +} +// 建立ws连接 +function websocketOpen (e) { + // console.log('ws连接成功') +} + +// 初始化weosocket +function initWebSocket () { + if (typeof (WebSocket) === 'undefined') { + Message.error('您的浏览器不支持WebSocket,无法获取数据') + return false + } + + const token = 'X-Token=' + getToken() + // ws请求完整地址 + const requstWsUrl = wsUrl + '?' + token + websock = new WebSocket(requstWsUrl) + + websock.onmessage = function (e) { + websocketonmessage(e) + } + websock.onopen = function () { + websocketOpen() + } + websock.onerror = function () { + Message.error('ws连接异常,请稍候重试') + errorCallback() + } + websock.onclose = function (e) { + websocketclose(e) + } +} + +/** + * 发起websocket请求函数 + * @param {string} url ws连接地址 + * @param {Object} agentData 传给后台的参数 + * @param {function} successCallback 接收到ws数据,对数据进行处理的回调函数 + * @param {function} errCallback ws连接错误的回调函数 + */ +export function sendWebsocket (url, agentData, successCallback, errCallback) { + wsUrl = url + initWebSocket() + messageCallback = successCallback + errorCallback = errCallback + websocketSend(agentData) +} + +/** + * 关闭websocket函数 + */ +export function closeWebsocket () { + if (websock) { + websock.close() // 关闭websocket + websock.onclose() // 关闭websocket + } +} +