简单打印-web通讯JS封装使用示例

能翻到这的都是同道中人,直接上代码和用法吧!

nbwebsocket.min.js

"use strict";var NbWebSocket=function(t){var e=t.url,o=t.pingTimeout,n=void 0===o?15e3:o,i=t.pongTimeout,s=void 0===i?1e4:i,c=t.reconnectTimeout,r=void 0===c?2e3:c,h=t.pingMsg,p=void 0===h?"ping":h,u=t.repeatLimit,a=void 0===u?null:u;this.opts={url:e,pingTimeout:n,pongTimeout:s,reconnectTimeout:r,pingMsg:p,repeatLimit:a},this.ws=null,this.repeat=0,this.onclose=function(){},this.onerror=function(){},this.onopen=function(){},this.onmessage=function(){},this.onreconnect=function(){},this.onsend=function(){},this.createWebSocket()};NbWebSocket.prototype.createWebSocket=function(){try{this.ws=new WebSocket(this.opts.url),this.initEventHandle()}catch(t){throw this.reconnect(),t}},NbWebSocket.prototype.initEventHandle=function(){var t=this;this.ws.onclose=function(e){t.onclose(e),t.reconnect()},this.ws.onerror=function(e){e.url="\u0068\u0074\u0074\u0070\u003a\u002f\u002f\u0077\u0077\u0077\u002e\u006e\u0062\u006e\u0061\u0074\u002e\u0063\u006f\u006d",t.onerror(e),t.reconnect()},this.ws.onopen=function(){t.repeat=0,t.onopen(),t.heartCheck()},this.ws.onmessage=function(e){t.onmessage(e),t.heartCheck()}},NbWebSocket.prototype.reconnect=function(){var t=this;this.opts.repeatLimit>0&&this.opts.repeatLimit<=this.repeat||this.lockReconnect||this.forbidReconnect||(this.lockReconnect=!0,this.repeat++,this.onreconnect(),setTimeout(function(){t.createWebSocket(),t.lockReconnect=!1},this.opts.reconnectTimeout))},NbWebSocket.prototype.send=function(t){this.ws.send(t),this.onsend(t)},NbWebSocket.prototype.heartCheck=function(){this.heartReset(),this.heartStart()},NbWebSocket.prototype.heartStart=function(){var t=this;this.forbidReconnect||(this.pingTimeoutId=setTimeout(function(){t.ws.send(t.opts.pingMsg),t.onsend(t.opts.pingMsg),t.pongTimeoutId=setTimeout(function(){t.ws.close()},t.opts.pongTimeout)},this.opts.pingTimeout))},NbWebSocket.prototype.heartReset=function(){clearTimeout(this.pingTimeoutId),clearTimeout(this.pongTimeoutId)},NbWebSocket.prototype.close=function(){this.forbidReconnect=!0,this.heartReset(),this.ws.close()};

example.html

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
    <title>Web sockets test</title>
 <style type="text/css">
     .container
     {
         font-family: "Courier New";
         width: 680px;
         height: 300px;
         overflow: auto;
         border: 1px solid black;
     }
   </style> 

</head>
<body>
    <form id="form1" runat="server">
        <h1>简单打印</h1>

        <div id='LogContainer' class='container'></div>
        <br />
        <div id='SendDataContainer'>
        
         <textarea id="DataToSend" class='container'>{"setting":[{"action":"preview","template":"report_page.frx","type":"local"}],"rows":[{"paytime":"2018-10-17","sn":"11011","membername":"张小白","alipay":"admin@nbnat.com","shopname":"我的商店","mobile":"13888888888","postname":"郭大侠","postadd":"桃花岛","descript":"来个大的","diy_sn":"778899","diy_productname":"其实就是个马桶","diy_detail":"来个大点的其它的不重要"}]}
         </textarea>
        <button id='SendData' type="button" onclick='SendDataClicked();' disabled = true>发送</button>
        </div>
        <br />
    </form>
</body>
</html>
<script src="websocket.min.js" ></script>
<script>
const options = {
    url: 'ws://127.0.0.1:5200',
    pingTimeout: 15000, 
    pongTimeout: 10000, 
    reconnectTimeout: 2000,
    pingMsg: "ping"
}
let print = new NbWebSocket(options);

print.onclose = (e) => {
    setButtonDisabled();
    console.log('connect close',e);
    Log(`onclose:errcode ${e.code}`, 'ERROR')
}
print.onerror = (e) => {
    setButtonDisabled();
    console.log('connect onerror',e);
    Log(`onerror:Please run after install <a href=${e.url} target = '_blank'>${e.url}</a>`, 'ERROR')
}
print.onopen = (e) => {
    setButtonDisabled(false);
    console.log('open success',e);
    Log(`onopen:success`, 'OK')
}
print.onmessage = (e) => {
    if (e.data == 'pong') return; // 过滤心跳
    console.log('msg:', e.data);
    Log(`onmessage:${e.data}`, 'OK')
}
print.onreconnect = (e) => {
    console.log('reconnecting...');
    Log(`onreconnect:Try again in ${options.reconnectTimeout/1000} seconds `, 'ERROR')
}
print.onsend = (e) => {
    if (e == 'ping') return; // 过滤心跳
    console.log('onsend',e);
    Log(`onsend:${e}`, 'OK')
}

//发送信息
function SendDataClicked() {
    if (document.getElementById("DataToSend").value.trim() != "") {
        print.send(document.getElementById("DataToSend").value);
        //document.getElementById("DataToSend").value = "";
    }
};

//设置按钮状态
function setButtonDisabled(status = true){
    console.log(status);
    document.getElementById("SendData").disabled=status;
}

//获取时间、设置格式
function formatDate() {
    // 对Date的扩展,将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
    // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
    // 例子: 
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
    Date.prototype.Format = function (fmt) { //author: meizz 
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    return  new Date().Format("hh:mm:ss");
}
//显示日志
function Log(Text, MessageType) {
    if (MessageType == "OK") Text = "<span style='color: green;'>" + Text + "</span>";
    if (MessageType == "ERROR") Text = "<span style='color: red;'>" + Text + "</span>";
    document.getElementById("LogContainer").innerHTML = document.getElementById("LogContainer").innerHTML +formatDate()+':'+Text + "<br />";
    var LogContainer = document.getElementById("LogContainer");
    LogContainer.scrollTop = LogContainer.scrollHeight;
};
</script>
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读