websocket.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. params = {
  34. inApp: true, // app内横幅提醒
  35. voice: true, // 声音提醒
  36. vibration: true, // 振动提醒
  37. messageType: '', //消息分类
  38. messageTitle: '', //通知标题
  39. messageContent: '中药煎配溯源管理来新处方啦!',
  40. messageImage: ''
  41. }
  42. uni.$appPush(params)
  43. uni.redirectTo({
  44. url:"/pages/index/index"
  45. })
  46. })
  47. //监听socket关闭
  48. uni.onSocketClose((res) => {
  49. console.log('WebSocket 已关闭!')
  50. this.isOpen = false
  51. })
  52. } catch (error) {
  53. console.log('err:' + error)
  54. }
  55. },
  56. //发送消息
  57. sendMessage(msg = '', successFunc = null, errorFunc = null) {
  58. if (!this.isOpen || !msg) {
  59. if (errorFunc) {
  60. errorFunc('未传消息内容或连接未打开!')
  61. }
  62. return
  63. }
  64. uni.sendSocketMessage({
  65. data: msg,
  66. success(res) {
  67. console.log('消息发送成功!')
  68. if (successFunc) {
  69. successFunc(res)
  70. }
  71. },
  72. fail(err) {
  73. console.log('消息发送失败!')
  74. if (errorFunc) {
  75. errorFunc(err)
  76. }
  77. }
  78. })
  79. },
  80. //关闭连接
  81. closeSocket() {
  82. if (!this.isOpen) {
  83. return
  84. }
  85. //关闭socket连接
  86. uni.closeSocket()
  87. }
  88. }
  89. export default _WEBSOCKET