index.vue 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <template>
  2. <div class="flex">
  3. <!-- 左侧:建立连接、发送消息 -->
  4. <el-card :gutter="12" class="w-1/2" shadow="always">
  5. <template #header>
  6. <div class="card-header">
  7. <span>连接</span>
  8. </div>
  9. </template>
  10. <div class="flex items-center">
  11. <span class="mr-4 text-lg font-medium"> 连接状态: </span>
  12. <el-tag :color="getTagColor">{{ status }}</el-tag>
  13. </div>
  14. <hr class="my-4" />
  15. <div class="flex">
  16. <el-input v-model="server" disabled>
  17. <template #prepend>服务地址</template>
  18. </el-input>
  19. <el-button :type="getIsOpen ? 'danger' : 'primary'" @click="toggleConnectStatus">
  20. {{ getIsOpen ? '关闭连接' : '开启连接' }}
  21. </el-button>
  22. </div>
  23. <p class="mt-4 text-lg font-medium">消息输入框</p>
  24. <hr class="my-4" />
  25. <el-input
  26. v-model="sendText"
  27. :autosize="{ minRows: 2, maxRows: 4 }"
  28. :disabled="!getIsOpen"
  29. clearable
  30. type="textarea"
  31. placeholder="请输入你要发送的消息"
  32. />
  33. <el-select v-model="sendUserId" class="mt-4" placeholder="请选择发送人">
  34. <el-option key="" label="所有人" value="" />
  35. <el-option
  36. v-for="user in userList"
  37. :key="user.id"
  38. :label="user.nickname"
  39. :value="user.id"
  40. />
  41. </el-select>
  42. <el-button :disabled="!getIsOpen" block class="ml-2 mt-4" type="primary" @click="handlerSend">
  43. 发送
  44. </el-button>
  45. </el-card>
  46. <!-- 右侧:消息记录 -->
  47. <el-card :gutter="12" class="w-1/2" shadow="always">
  48. <template #header>
  49. <div class="card-header">
  50. <span>消息记录</span>
  51. </div>
  52. </template>
  53. <div class="max-h-80 overflow-auto">
  54. <ul>
  55. <li v-for="msg in messageList.reverse()" :key="msg.time" class="mt-2">
  56. <div class="flex items-center">
  57. <span class="text-primary mr-2 font-medium">收到消息:</span>
  58. <span>{{ formatDate(msg.time) }}</span>
  59. </div>
  60. <div>
  61. {{ msg.text }}
  62. </div>
  63. </li>
  64. </ul>
  65. </div>
  66. </el-card>
  67. </div>
  68. </template>
  69. <script lang="ts" setup>
  70. import { formatDate } from '@/utils/formatTime'
  71. import { useWebSocket } from '@vueuse/core'
  72. import { getAccessToken } from '@/utils/auth'
  73. import * as UserApi from '@/api/system/user'
  74. defineOptions({ name: 'InfraWebSocket' })
  75. const message = useMessage() // 消息弹窗
  76. const server = ref(
  77. (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') + '?token=' + getAccessToken()
  78. ) // WebSocket 服务地址
  79. const getIsOpen = computed(() => status.value === 'OPEN') // WebSocket 连接是否打开
  80. const getTagColor = computed(() => (getIsOpen.value ? 'success' : 'red')) // WebSocket 连接的展示颜色
  81. /** 发起 WebSocket 连接 */
  82. const { status, data, send, close, open } = useWebSocket(server.value, {
  83. autoReconnect: false,
  84. heartbeat: true
  85. })
  86. /** 监听接收到的数据 */
  87. const messageList = ref([] as { time: number; text: string }[]) // 消息列表
  88. watchEffect(() => {
  89. if (!data.value) {
  90. return
  91. }
  92. try {
  93. // 1. 收到心跳
  94. if (data.value === 'pong') {
  95. // state.recordList.push({
  96. // text: '【心跳】',
  97. // time: new Date().getTime()
  98. // })
  99. return
  100. }
  101. // 2.1 解析 type 消息类型
  102. const jsonMessage = JSON.parse(data.value)
  103. const type = jsonMessage.type
  104. const content = JSON.parse(jsonMessage.content)
  105. if (!type) {
  106. message.error('未知的消息类型:' + data.value)
  107. return
  108. }
  109. // 2.2 消息类型:demo-message-receive
  110. if (type === 'demo-message-receive') {
  111. const single = content.single
  112. if (single) {
  113. messageList.value.push({
  114. text: `【单发】用户编号(${content.fromUserId}):${content.text}`,
  115. time: new Date().getTime()
  116. })
  117. } else {
  118. messageList.value.push({
  119. text: `【群发】用户编号(${content.fromUserId}):${content.text}`,
  120. time: new Date().getTime()
  121. })
  122. }
  123. return
  124. }
  125. // 2.3 消息类型:notice-push
  126. if (type === 'notice-push') {
  127. messageList.value.push({
  128. text: `【系统通知】:${content.title}`,
  129. time: new Date().getTime()
  130. })
  131. return
  132. }
  133. message.error('未处理消息:' + data.value)
  134. } catch (error) {
  135. message.error('处理消息发生异常:' + data.value)
  136. console.error(error)
  137. }
  138. })
  139. /** 发送消息 */
  140. const sendText = ref('') // 发送内容
  141. const sendUserId = ref('') // 发送人
  142. const handlerSend = () => {
  143. // 1.1 先 JSON 化 message 消息内容
  144. const messageContent = JSON.stringify({
  145. text: sendText.value,
  146. toUserId: sendUserId.value
  147. })
  148. // 1.2 再 JSON 化整个消息
  149. const jsonMessage = JSON.stringify({
  150. type: 'demo-message-send',
  151. content: messageContent
  152. })
  153. // 2. 最后发送消息
  154. send(jsonMessage)
  155. sendText.value = ''
  156. }
  157. /** 切换 websocket 连接状态 */
  158. const toggleConnectStatus = () => {
  159. if (getIsOpen.value) {
  160. close()
  161. } else {
  162. open()
  163. }
  164. }
  165. /** 初始化 **/
  166. const userList = ref<any[]>([]) // 用户列表
  167. onMounted(async () => {
  168. // 获取用户列表
  169. userList.value = await UserApi.getSimpleUserList()
  170. })
  171. </script>