liuxiaolong
2019-05-06 2ab7a76a38fbf8fa107bf6371f5410ba54e1d394
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* eslint-disable */
import router from '@/router'
// import Websocket from 'websocket'
import {
  w3cwebsocket as WebSocketClient
} from 'websocket'
import toasted from '@/components/common/toasted'
// var WebSocketClient = require('websocket').w3cwebsocket;
class BaseModel {
  static serverOptions = {}
  static BASE_WS_URL = 'ws://192.168.1.173:6678';
 
  static startWsConn(path, onMsg, onError, onClosed, onGoClose) {
    return new Promise((resolve, reject) => {
      // var client = new Websocket.client();
 
      var client = new WebSocketClient(`${BaseModel.BASE_WS_URL}${path}`)
      // var client = new WebSocketClient(`${BaseModel.BASE_WS_URL}${path}`, 'echo-protocol');
 
      client.onerror = function () {
        console.log('Connection Error')
        reject('Connection Error')
      }
 
      client.onopen = function () {
        resolve(client)
        console.log('WebSocket Client Connected---成功调用')
      }
 
      client.onclose = function (obj) {
        if (onClosed instanceof Function) {
          onClosed(obj)
        }
        console.log('echo-protocol Client Closed')
      }
      client.onmessage = function (e) {
        if (onMsg instanceof Function) {
          let msg = JSON.parse(e.data)
          onMsg(msg)
          // if (msg.hasOwnProperty('data') && msg.success) {
          //   onMsg(msg.data)
          // } else {
          //   toasted({
          //     type: 'error',
          //     message: msg.message
          //   })
          // }
        }
      }
      // 用于关闭websocket链接
      onGoClose && onGoClose(client)
 
      // console.log(_this.onGoClose,'_this.onGoClose');
      // 路由跳转关闭websocket链接
      router.afterEach(() => {
        client.close()
      })
    })
  }
 
  // async getData(conditions){
  //
  //     let serverOption = serverOptions.getAreaList;
  //     let data = [];
  //     try{
  //         data = await BaseModel.requestPromise(serverOption );
  //     }catch (ex){
  //       console.log('ex',ex)
  //     }
  //     return data;
  // }
}
export default BaseModel