| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- import { Message } from 'element-ui'
- var wsc2={
- url : 'ws://127.0.0.1:9999',
- ws:null,
- is_online:false,
- timer_ping:null,
- timer_close:null,
- interval_ping:10000,
- interval_close:5000,
- init:function(callback){
- var self=this;
- Message({
- type:'success',
- message: '扫描程序正在启动,请稍后……'
- })
- self.ws= new WebSocket(self.url);
- self.ws.onopen = function(evt) {
- // console.log("Connection open ...");
- self.is_onlien=true;
- self.ws.send("client connect success");
-
- start_heartbeat();
- };
-
- self.ws.onmessage = function(evt) {
- console.log("打印扫描仪返回的evt: " +evt.data);
- if(evt.data=="ping"){
- self.send("pong");
- // console.log("on ping");
- }
- else if(evt.data=="pong"){
- // console.log("on pong");
- }
- else{
- // console.log( "Received Message: " + evt.data);
- let objectData=JSON.parse(evt.data);
- console.log("扫描仪返回的数据",objectData);
- if (objectData.Data) {
- let obj=JSON.parse(objectData.Data.data_string);
- console.log("打印返回的图片地址",obj);
- // let obj={
- // code:200,
- // data:objectData.entity.fi_full_name,
- // msg:'图片扫描成功',
- // };
- // callback(obj);// 通过回调函数返回图片地址
-
- }
-
- if (objectData.code === 509) {
- // Message({
- // type: 'error',
- // message: '服务器错误,请检查日志'
- // })
- } else if (JSON.parse(evt.data).code === 502) {
- Message({
- type: 'error',
- message: '未检测到纸张或卡纸'
- })
- self.ws.close();//关闭链接
- }
- else if (JSON.parse(evt.data).code === 200) {
- Message({
- type: 'success',
- message: '扫描仪启动成功!'
- })
- }
- }
-
- clearTimeout(self.timer_close);
- clearTimeout(self.timer_ping);
- start_heartbeat();
- };
-
- self.ws.onclose = function(evt) {
- console.log("连接关闭");
- };
-
- self.ws.onerror=function(evt){
- console.log(evt);
- };
- //心跳检测
- function start_heartbeat(){
- self.timer_ping=setTimeout(function(){
- self.send("ping");//发送一次 "ping" 消息给服务器。
-
- //设置关闭定时器,如果超过 self.interval_close 毫秒没有收到服务器的响应,则认为连接已经断开,关闭 WebSocket 连接。
- self.timer_close=setTimeout(function(){
- self.ws.close();
- self.is_online=false;
- on_offline();//处理离线逻辑方法
- },self.interval_close);
- },self.interval_ping);//每隔 self.interval_ping 毫秒
- }
- //离线处理逻辑
- function on_offline(){
-
- }
- },
- send:function(data){
- if (this.ws.readyState === this.ws.OPEN)
- {
- console.log("发送数据:" + data);
- this.ws.send(data);
- } else {
- Message({
- type: 'error',
- message: '请确认扫描客户端是否已经启动',
- duration: 5000
- });
- }
- // console.log("发送数据:"+data);
- // try {
- // this.ws.send(data);
- // } catch(e) {
- // Message({
- // type: 'error',
- // message: '请确认扫描客户端是否已经启动'
- // })
- // }
-
- },
- }
- export default wsc2
|