liuying
2024-11-11 62ec1f19c3444695e21f1fe97472261ce3082075
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import store from '@/store'
import { Modal, message } from 'ant-design-vue'
import * as SignalR from '@microsoft/signalr'
 
const EventEmitter = require('events')
 
const defaultOptions = {
  log: false
}
 
class SocketConnection extends EventEmitter {
  constructor(connection, options = {}) {
    super()
    this.connection = connection
    this.options = Object.assign(defaultOptions, options)
    this.listened = []
    this.toSend = []
    this.offline = false
    this.socket = undefined
  }
 
  /**
   * 同一种消息只定义一次
   *
   * @param {string| symbol} event
   * @param {(...args: any[]) => void} listener
   * @memberof SocketConnection
   */
  one(event, listener) {
    if (this.listeners(event).length === 0) {
      this.on(event, listener)
    }
  }
 
  async _initialize() {
    if(this.socket == undefined){
        return;
    }
    try {
      await this.socket.start()
      this.emit('onstart')
      if (this.offline) {
        this.emit('onrestart')
      }
      this.offline = false
    } catch (error) {
      setTimeout(async () => {
        await this._initialize()
      }, 5000)
    }
  }
 
  async start(token) {
    // 组件重新加载时, 如果 socket 存在, 不需要新建
    if (!this.socket) {
      this.socket = new SignalR.HubConnectionBuilder()
        .configureLogging(SignalR.LogLevel.Information)
        .withUrl(`/hubs/chathub`, {
          accessTokenFactory: () => token,
          skipNegotiation: true,
          transport: SignalR.HttpTransportType.WebSockets
        })
        .build()
 
      this.socket.onclose(async () => {
        this.offline = true
        this.emit('onclose')
        await this._initialize()
      })
 
      this.socket.on('ForceExist', () => {
        // 关闭连接
        this.socket.stop()
        // 必须
        this.socket = undefined
        store
          .dispatch('Logout')
          .then(() => {
            Modal.success({
              title: '消息',
              content: '你已被强制下线',
              keyboard: false,
              onOk: () => {
                window.location.reload()
              }
            })
          })
          .catch(err => {
            message.error({
              title: '错误',
              description: err.message
            })
          })
      })
 
      this.socket.on('SingleLoginForceExist', () => {
        // 关闭连接
        this.socket.stop()
        store
          .dispatch('Logout')
          .then(() => {
            Modal.success({
              title: '消息',
              content: '您的账号已在其他地方登录,被强制下线',
              keyboard: false,
              onOk: () => {
                window.location.reload()
              }
            })
          })
          .catch(err => {
            message.error({
              title: '错误',
              description: err.message
            })
          })
      })
 
      await this._initialize()
    }
  }
 
  async authenticate(token) {
    await this.start(token)
  }
 
  listen(method) {
    if (this.offline) return
 
    if (this.listened.some(v => v === method)) return
    this.listened.push(method)
 
    this.one('onstart', () => {
      this.listened.forEach(method => {
        this.socket.on(method, data => {
          if (this.options.log) {
          }
 
          this.emit(method, data)
        })
      })
    })
  }
 
  send(methodName, ...args) {
    if (this.options.log) {
    }
    if (this.offline) return
 
    if (this.socket) {
      this.socket.send(methodName, ...args)
      return
    }
 
    this.one('onstart', () => this.socket.send(methodName, ...args))
  }
 
  async invoke(methodName, ...args) {
    if (this.options.log) {
    }
    if (this.offline) return false
 
    if (this.socket) {
      return this.socket.invoke(methodName, ...args)
    }
 
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => this.one('onstart', () => resolve(this.socket.invoke(methodName, ...args))))
  }
}
 
if (!SignalR) {
  throw new Error('[Vue-SignalR] Cannot locate signalr-client')
}
 
function install(Vue, connection) {
  if (!connection) {
    throw new Error('[Vue-SignalR] Cannot locate connection')
  }
 
  const Socket = new SocketConnection(connection)
 
  Vue.socket = Socket
 
  Object.defineProperties(Vue.prototype, {
    $socket: {
      get() {
        return Socket
      }
    }
  })
 
  Vue.mixin({
    created() {
      if (this.$options.sockets) {
        const methods = Object.getOwnPropertyNames(this.$options.sockets)
 
        methods.forEach(method => {
          Socket.listen(method)
 
          Socket.one(method, data => this.$options.sockets[method].call(this, data))
        })
      }
 
      if (this.$options.subscribe) {
        Socket.one('authenticated', () => {
          this.$options.subscribe.forEach(channel => {
            Socket.invoke('join', channel)
          })
        })
      }
    }
  })
}
 
export default install