当前位置:   article > 正文

Netty - 从启蒙到搬砖(完整应用篇)(前端 Vue 篇)_netty 实现vue 前端交互

netty 实现vue 前端交互

后端篇:https://lux-sun.blog.csdn.net/article/details/101352493

 

前端篇


1、在 main.js 里赋值给 this 

  1. // main.js
  2. import websocket from '@/assets/js/websocket'
  3. Vue.prototype.websocket = websocket

2、 在首页 mounted 钩子函数里开启长连接

  1. // index.vue
  2. mounted () {
  3. this.websocket.initWebSocket() // 开启长连接
  4. }

3、所有的业务都在这里处理,无需其它地方再调用 websocket.js 里的函数

  1. // websocket.js
  2. import cookie from '@/assets/js/cookieUtil'
  3. import store from '@/store'
  4. import { Notification } from 'element-ui'
  5. import goodorder from '@/api/goodorderBG'
  6. let websocketURL = 'wss://xxx/websocket'
  7. let heartbeatTime = 20000 // nginx 60s 限制,这里 20s 一次心跳
  8. let reconnectionTime = 10000 // 断线后 10s 尝试一次重连
  9. let ws = null
  10. let that = null
  11. let reconnection = true
  12. let reconnectionCount = 0
  13. export default {
  14. initWebSocket(){
  15. console.log('初始化websocket');
  16. that = this
  17. if(ws!==null){
  18. this.closeWebsocket()
  19. }
  20. ws = new WebSocket(websocketURL);
  21. ws.onmessage = this.websocketOnMessage;
  22. ws.onopen = this.websocketOnOpen;
  23. ws.onerror = this.websocketOnError;
  24. ws.onclose = this.websocketClose;
  25. },
  26. websocketOnOpen(){ // 连接建立之后执行send方法发送数据
  27. Notification({
  28. title: '已连接到服务器',
  29. message: '成功与服务器建立联机',
  30. type: 'success',
  31. offset: 60 // 偏移量
  32. })
  33. reconnectionCount = 0
  34. let account = JSON.parse(cookie.getCookie())
  35. let actions = {"operand":1, "userId":account.userInfo.userId}
  36. that.websocketSend(JSON.stringify(actions)) // 绑定userId
  37. that.initData() // 初始化websocket建立数据
  38. },
  39. websocketOnError(){ // 连接建立失败重连
  40. },
  41. websocketOnMessage(e){ // 数据接收
  42. let data = JSON.parse(e.data)
  43. if(data.status === 1){ // 1:连接无异常
  44. setTimeout(() => {
  45. that.heartbeat()
  46. },heartbeatTime) // 心跳包
  47. }else if(data.status === 2) { // 2:有新的业务逻辑消息需要处理
  48. let info = JSON.parse(data.data)
  49. if(info.type === 1){ // 家长申请订单
  50. store.dispatch('websocket/changeAuditOrderNum',info.data.total)
  51. Notification({
  52. title: '您的家长申请订单数量有新的变化',
  53. message: data.msg,
  54. offset: 60
  55. });
  56. }
  57. }
  58. },
  59. websocketSend(data){ // 数据发送
  60. ws.send(data);
  61. },
  62. websocketClose(e){ // 关闭
  63. if(reconnection){
  64. if(reconnectionCount === 0){
  65. Notification({
  66. title: '连接意外断开',
  67. message: '正在尝试重新建立连接',
  68. type: 'error',
  69. offset: 60
  70. })
  71. }
  72. setTimeout(() => {
  73. console.log('尝试重连')
  74. reconnectionCount += 1
  75. that.initWebSocket()
  76. },reconnectionTime) // 重新连接
  77. }else{
  78. // 不重连但是将重连状态改为true
  79. console.log('停止连接')
  80. reconnection = true
  81. }
  82. },
  83. closeWebsocket(){ // 主动关闭websocket
  84. try {
  85. ws.close()
  86. ws = null
  87. }catch (e) { }
  88. },
  89. heartbeat(){
  90. let actions = {"operand":2};
  91. this.websocketSend(JSON.stringify(actions));
  92. },
  93. setReconnection(rc){ // 退出登录会调用,且设置false
  94. reconnection = rc
  95. },
  96. initData(){
  97. // 获取申请订单数
  98. goodorder.getTempGoodorderCount(
  99. {
  100. status: 0,
  101. type: 0
  102. }
  103. ).then(res => {
  104. if(res.success){
  105. store.dispatch('websocket/changeAuditOrderNum',res.data)
  106. } else if (res.nullwarn) {
  107. store.dispatch('websocket/changeAuditOrderNum',0)
  108. } else {
  109. this.$message({ type: 'error', message: res.msg })
  110. }
  111. }).catch(error => {
  112. if(error !== 'noLogin'){
  113. this.$message({ type: 'error', message: '系统错误' })
  114. }
  115. })
  116. }
  117. }

4、这里用到了 Vuex,我们稍微看下

  1. // store/index.js
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. Vue.use(Vuex)
  5. const modulesFiles = require.context('./modules', false, /\.js$/)
  6. const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  7. // set './app.js' => 'app'
  8. const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  9. const value = modulesFiles(modulePath)
  10. modules[moduleName] = value.default
  11. return modules
  12. }, {})
  13. const store = new Vuex.Store({
  14. modules
  15. })
  16. export default store
  1. // store/modules/websocket.js
  2. const state = {
  3. tempOrderNum: 0,
  4. noticeNum: 0
  5. }
  6. const mutations = {
  7. changeTempOrderNum: (state,num) => {
  8. state.tempOrderNum = num
  9. state.noticeNum = state.tempOrderNum
  10. }
  11. }
  12. const actions = {
  13. changeTempOrderNum({ commit },num) {
  14. commit('changeTempOrderNum',num)
  15. }
  16. }
  17. export default {
  18. namespaced: true,
  19. state,
  20. mutations,
  21. actions
  22. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/404331
推荐阅读
相关标签
  

闽ICP备14008679号