石墨消解仪
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.

63 lines
1.4 KiB

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. }
  34. }
  35. // 消息发送
  36. msg(param) {
  37. if (param === 'heartbeat') {
  38. this.ws.send(param)
  39. } else {
  40. this.ws.send(JSON.stringify(param))
  41. }
  42. }
  43. // 延迟发送
  44. timeout(param) {
  45. setTimeout(() => {
  46. this.msg(param)
  47. }, 2000)
  48. }
  49. send(param) {
  50. if (this.ws.readyState === this.ws.OPEN) {
  51. this.msg(param)
  52. } else if (this.ws.readyState === this.ws.CONNECTING) {
  53. this.timeout(param)
  54. } else {
  55. this.timeout(param)
  56. }
  57. }
  58. }