大空间消毒机
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.5 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. export default class Socket {
  2. constructor(url, protocols) {
  3. this.url = url
  4. this.protocols = protocols
  5. this.ws = null
  6. this.reconnectTimeout = 2000
  7. this.maxReconnectTimes = 100
  8. this.reconnectTimes = 0
  9. }
  10. connect() {
  11. this.ws = new WebSocket(this.url, this.protocols)
  12. this.ws.onopen = () => {
  13. console.log('WebSocket连接成功')
  14. this.reconnectTimes = 0
  15. }
  16. this.ws.onclose = () => {
  17. console.log('WebSocket断开连接')
  18. this.reconnect()
  19. }
  20. this.ws.onerror = err => {
  21. console.log('WebSocket连接出错', err)
  22. }
  23. }
  24. reconnect() {
  25. if (this.reconnectTimes < this.maxReconnectTimes) {
  26. setTimeout(() => {
  27. this.connect()
  28. this.reconnectTimes++
  29. }, this.reconnectTimeout)
  30. } else {
  31. console.log('WebSocket重连超过最大次数,放弃重连')
  32. // window.location.href = 'http://127.0.0.1/#/login'
  33. }
  34. }
  35. // 消息发送
  36. msg(param) {
  37. if (param === 'heartbeat') {
  38. this.ws.send(param)
  39. } else {
  40. if (param.command != 'getState') {
  41. console.log(param)
  42. }
  43. this.ws.send(JSON.stringify(param))
  44. }
  45. }
  46. // 延迟发送
  47. timeout(param) {
  48. setTimeout(() => {
  49. this.msg(param)
  50. }, 2000)
  51. }
  52. send(param) {
  53. if (this.ws.readyState === this.ws.OPEN) {
  54. this.msg(param)
  55. } else if (this.ws.readyState === this.ws.CONNECTING) {
  56. this.timeout(param)
  57. } else {
  58. this.timeout(param)
  59. }
  60. }
  61. }