websocket.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. const _WEBSOCKET = {
  2. //是否打开连接
  3. isOpen: false,
  4. //连接socket
  5. connectSocket(url,successFunc = null, errorFunc = null) {
  6. try {
  7. //连接socket
  8. uni.connectSocket({
  9. url,
  10. success() {
  11. console.log('websocket连接成功!')
  12. }
  13. })
  14. //监听socket连接
  15. uni.onSocketOpen((res) => {
  16. this.isOpen = true
  17. console.log('WebSocket连接已打开!')
  18. if (successFunc) {
  19. successFunc(res)
  20. }
  21. })
  22. //监听socket连接失败
  23. uni.onSocketError((res) => {
  24. this.isOpen = false
  25. console.log('WebSocket连接打开失败,请检查!')
  26. if (errorFunc) {
  27. errorFunc(res)
  28. }
  29. })
  30. //监听收到消息
  31. uni.onSocketMessage((res) => {
  32. console.log('收到服务器内容:' + res.data)
  33. // const params = {
  34. // inApp: true, // app内横幅提醒
  35. // voice: true, // 声音提醒
  36. // vibration: true, // 振动提醒
  37. // messageType: '', //消息分类
  38. // messageTitle: '', //通知标题
  39. // messageContent: '中药煎配溯源管理来新处方啦!',
  40. // messageImage: ''
  41. // }
  42. // #ifdef APP-ANDROID
  43. const plugin = uni.requireNativePlugin("DCloud-PushSound");
  44. plugin.setCustomPushChannel({
  45. soundName: "tips",
  46. channelId: "消息通知",
  47. channelDesc:"中药煎配溯源管理来新处方啦",
  48. enableLights:true,
  49. enableVibration:true,
  50. importance:4,
  51. lockscreenVisibility:1
  52. });
  53. // #endif
  54. uni.redirectTo({
  55. url:"/pages/index/index"
  56. })
  57. })
  58. //监听socket关闭
  59. uni.onSocketClose((res) => {
  60. console.log('WebSocket 已关闭!')
  61. this.isOpen = false
  62. })
  63. } catch (error) {
  64. console.log('err:' + error)
  65. }
  66. },
  67. //发送消息
  68. sendMessage(msg = '', successFunc = null, errorFunc = null) {
  69. if (!this.isOpen || !msg) {
  70. if (errorFunc) {
  71. errorFunc('未传消息内容或连接未打开!')
  72. }
  73. return
  74. }
  75. uni.sendSocketMessage({
  76. data: msg,
  77. success(res) {
  78. console.log('消息发送成功!')
  79. if (successFunc) {
  80. successFunc(res)
  81. }
  82. },
  83. fail(err) {
  84. console.log('消息发送失败!')
  85. if (errorFunc) {
  86. errorFunc(err)
  87. }
  88. }
  89. })
  90. },
  91. //关闭连接
  92. closeSocket() {
  93. if (!this.isOpen) {
  94. return
  95. }
  96. //关闭socket连接
  97. uni.closeSocket()
  98. }
  99. }
  100. export default _WEBSOCKET