web-socket.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. function showModal(title, content) {
  2. wx.showModal({
  3. title,
  4. content,
  5. showCancel: false
  6. })
  7. }
  8. function showSuccess(title) {
  9. wx.showToast({
  10. title,
  11. icon: 'success',
  12. duration: 1000
  13. })
  14. }
  15. Page({
  16. onShareAppMessage() {
  17. return {
  18. title: 'Web Socket',
  19. path: 'page/API/pages/web-socket/web-socket'
  20. }
  21. },
  22. data: {
  23. socketStatus: 'closed'
  24. },
  25. onLoad() {
  26. const self = this
  27. self.setData({
  28. hasLogin: true
  29. })
  30. // qcloud.setLoginUrl(loginUrl)
  31. // qcloud.login({
  32. // success: function(result) {
  33. // console.log('登录成功', result)
  34. // self.setData({
  35. // hasLogin: true
  36. // })
  37. // },
  38. // fail: function(error) {
  39. // console.log('登录失败', error)
  40. // }
  41. // })
  42. },
  43. onUnload() {
  44. this.closeSocket()
  45. },
  46. toggleSocket(e) {
  47. const turnedOn = e.detail.value
  48. if (turnedOn && this.data.socketStatus === 'closed') {
  49. this.openSocket()
  50. } else if (!turnedOn && this.data.socketStatus === 'connected') {
  51. const showSuccess = true
  52. this.closeSocket(showSuccess)
  53. }
  54. },
  55. openSocket() {
  56. // var socket = this.socket = new qcloud.Tunnel(tunnelUrl)
  57. wx.onSocketOpen(() => {
  58. console.log('WebSocket 已连接')
  59. showSuccess('Socket已连接')
  60. this.setData({
  61. socketStatus: 'connected',
  62. waitingResponse: false
  63. })
  64. })
  65. wx.onSocketClose(() => {
  66. console.log('WebSocket 已断开')
  67. this.setData({socketStatus: 'closed'})
  68. })
  69. wx.onSocketError(error => {
  70. showModal('发生错误', JSON.stringify(error))
  71. console.error('socket error:', error)
  72. this.setData({
  73. loading: false
  74. })
  75. })
  76. // 监听服务器推送消息
  77. wx.onSocketMessage(message => {
  78. showSuccess('收到信道消息')
  79. console.log('socket message:', message)
  80. this.setData({
  81. loading: false
  82. })
  83. })
  84. // 打开信道
  85. wx.connectSocket({
  86. url: 'wss://echo.websocket.org',
  87. })
  88. },
  89. closeSocket() {
  90. if (this.data.socketStatus === 'connected') {
  91. wx.closeSocket({
  92. success: () => {
  93. showSuccess('Socket已断开')
  94. this.setData({socketStatus: 'closed'})
  95. }
  96. })
  97. }
  98. },
  99. sendMessage() {
  100. if (this.data.socketStatus === 'connected') {
  101. wx.sendSocketMessage({
  102. data: 'Hello, Miniprogram!'
  103. })
  104. }
  105. },
  106. })