新型管道消毒机前端代码
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.

65 lines
1.4 KiB

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