拉杆箱消毒机
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.

70 lines
1.5 KiB

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