App.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <!-- <template>
  2. <div class="app">
  3. <router-view class="page-top-space"></router-view>
  4. </div>
  5. </template> -->
  6. <script setup>
  7. import { onShow, onHide, onLaunch } from '@dcloudio/uni-app'
  8. import websocket from '@/static/websocket.js'
  9. //定义定时器
  10. let globalTimer = null
  11. onLaunch(async()=> {
  12. console.log('App onLaunch')
  13. // uni.getSystemInfo({
  14. // success: function(e) {
  15. // // Vue.prototype.StatusBar = e.statusBarHeight;
  16. // console.log("e.statusBarHeight", e.statusBarHeight)
  17. // if (e.platform == 'android') {
  18. // // Vue.prototype.CustomBar = e.statusBarHeight + 50;
  19. // console.log('CustomBar', e.statusBarHeight + 50)
  20. // } else {
  21. // console.log('CustomBar', e.statusBarHeight + 45)
  22. // };
  23. // }
  24. // })
  25. })
  26. onShow(()=>{
  27. console.log('App Show')
  28. uni.$on('login',(data)=>{
  29. try {
  30. //建立socket连接
  31. websocket.connectSocket(`wss://localhost:8005/webSocket/sentMessage${data.userId}`,() => {
  32. //如果连接成功则发送心跳检测
  33. heartBeatTest()
  34. })
  35. } catch (error) {
  36. console.log('App err:' + error)
  37. }
  38. })
  39. })
  40. onHide(()=>{
  41. console.log('App Hide')
  42. //关闭socket
  43. uni.$off('login', (data)=>{
  44. websocket.closeSocket()
  45. })
  46. })
  47. const heartBeatTest=()=> {
  48. //清除定时器
  49. clearInterval(globalTimer)
  50. //开启定时器定时检测心跳
  51. globalTimer = setInterval(() => {
  52. //发送消息给服务端
  53. websocket.sendMessage(
  54. JSON.stringify({ action: 'ping'}), //与服务端约定好消息格式
  55. null,
  56. () => {
  57. //如果失败则清除定时器
  58. clearInterval(globalTimer)
  59. }
  60. )
  61. }, 10000)
  62. }
  63. </script>
  64. <style>
  65. /*每个页面公共css */
  66. /* page{
  67. padding-top: 0;
  68. } */
  69. /* @import "@/static/iconfont.css" */
  70. .main{
  71. background-color: #bcbcbc;
  72. display: flex;
  73. flex-direction:column;
  74. width: 1200px;
  75. /* height: 2000px; */
  76. }
  77. </style>