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

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