websocket.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { playAudio } from '@/utils/audio.js'
  2. const _WEBSOCKET = {
  3. //是否打开连接
  4. isOpen: false,
  5. //连接socket
  6. connectSocket(url,successFunc = null, errorFunc = null) {
  7. try {
  8. //连接socket
  9. uni.connectSocket({
  10. url,
  11. success() {
  12. console.log('websocket连接成功!')
  13. }
  14. })
  15. //监听socket连接
  16. uni.onSocketOpen((res) => {
  17. this.isOpen = true
  18. console.log('WebSocket连接已打开!')
  19. if (successFunc) {
  20. successFunc(res)
  21. }
  22. })
  23. //监听socket连接失败
  24. uni.onSocketError((res) => {
  25. this.isOpen = false
  26. console.log('WebSocket连接打开失败,请检查!')
  27. if (errorFunc) {
  28. errorFunc(res)
  29. }
  30. })
  31. //监听收到消息
  32. uni.onSocketMessage((res) => {
  33. console.log('收到服务器内容:' + res.data)
  34. playAudio()
  35. uni.showToast({
  36. title: '您有新的单子',
  37. duration: 2000
  38. });
  39. // uni.redirectTo({
  40. // url:"/pages/index/index?tips=1"
  41. // })
  42. })
  43. //监听socket关闭
  44. uni.onSocketClose((res) => {
  45. console.log('WebSocket 已关闭!')
  46. this.isOpen = false
  47. })
  48. } catch (error) {
  49. console.log('err:' + error)
  50. }
  51. },
  52. //发送消息
  53. sendMessage(msg = '', successFunc = null, errorFunc = null) {
  54. if (!this.isOpen || !msg) {
  55. if (errorFunc) {
  56. errorFunc('未传消息内容或连接未打开!')
  57. }
  58. return
  59. }
  60. uni.sendSocketMessage({
  61. data: msg,
  62. success(res) {
  63. console.log('消息发送成功!')
  64. if (successFunc) {
  65. successFunc(res)
  66. }
  67. },
  68. fail(err) {
  69. console.log('消息发送失败!')
  70. if (errorFunc) {
  71. errorFunc(err)
  72. }
  73. }
  74. })
  75. },
  76. //关闭连接
  77. closeSocket() {
  78. if (!this.isOpen) {
  79. return
  80. }
  81. //关闭socket连接
  82. uni.closeSocket()
  83. }
  84. }
  85. export default _WEBSOCKET