index.vue 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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>{{ t('infra.connection') }}</span>
  8. </div>
  9. </template>
  10. <div class="flex items-center">
  11. <span class="mr-4 text-lg font-medium"> {{ t('infra.connectionStatus') }}: </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>{{ t('infra.serviceAddress') }}</template>
  18. </el-input>
  19. <el-button :type="getIsOpen ? 'danger' : 'primary'" @click="toggleConnectStatus">
  20. {{ getIsOpen ? t('infra.closeConnection') : t('infra.openConnection') }}
  21. </el-button>
  22. </div>
  23. <p class="mt-4 text-lg font-medium">{{ t('infra.messageInputBox') }}</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="t('infra.pleaseEnterMessageSend')"
  32. />
  33. <el-select v-model="sendUserId" class="mt-4" :placeholder="t('infra.pleaseSelectSender')">
  34. <el-option key="" :label="t('infra.allPeople')" 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. {{ t('infra.sent') }}
  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>{{ t('infra.messageRecord') }}</span>
  51. </div>
  52. </template>
  53. <div class="max-h-80 overflow-auto">
  54. <ul>
  55. <li v-for="msg in messageReverseList" :key="msg.time" class="mt-2">
  56. <div class="flex items-center">
  57. <span class="text-primary mr-2 font-medium">{{ t('infra.messageReceived') }}:</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. const { t } = useI18n()
  75. defineOptions({ name: 'InfraWebSocket' })
  76. const message = useMessage() // 消息弹窗
  77. const server = ref(
  78. (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') + '?token=' + getAccessToken()
  79. ) // WebSocket 服务地址
  80. const getIsOpen = computed(() => status.value === 'OPEN') // WebSocket 连接是否打开
  81. const getTagColor = computed(() => (getIsOpen.value ? 'success' : 'red')) // WebSocket 连接的展示颜色
  82. /** 发起 WebSocket 连接 */
  83. const { status, data, send, close, open } = useWebSocket(server.value, {
  84. autoReconnect: false,
  85. heartbeat: true
  86. })
  87. /** 监听接收到的数据 */
  88. const messageList = ref([] as { time: number; text: string }[]) // 消息列表
  89. const messageReverseList = computed(() => messageList.value.slice().reverse())
  90. watchEffect(() => {
  91. if (!data.value) {
  92. return
  93. }
  94. try {
  95. // 1. 收到心跳
  96. if (data.value === 'pong') {
  97. // state.recordList.push({
  98. // text: '【心跳】',
  99. // time: new Date().getTime()
  100. // })
  101. return
  102. }
  103. // 2.1 解析 type 消息类型
  104. const jsonMessage = JSON.parse(data.value)
  105. const type = jsonMessage.type
  106. const content = JSON.parse(jsonMessage.content)
  107. if (!type) {
  108. message.error(t('infra.unknownMessageType') + data.value)
  109. return
  110. }
  111. // 2.2 消息类型:demo-message-receive
  112. if (type === 'demo-message-receive') {
  113. const single = content.single
  114. if (single) {
  115. messageList.value.push({
  116. text: `${t('infra.groupNoticUserCode')}(${content.fromUserId}):${content.text}`,
  117. time: new Date().getTime()
  118. })
  119. } else {
  120. messageList.value.push({
  121. text: `${t('infra.groupSendingUserNumber')}(${content.fromUserId}):${content.text}`,
  122. time: new Date().getTime()
  123. })
  124. }
  125. return
  126. }
  127. // 2.3 消息类型:notice-push
  128. if (type === 'notice-push') {
  129. messageList.value.push({
  130. text: `${t('infra.systemNotification')}${content.title}`,
  131. time: new Date().getTime()
  132. })
  133. return
  134. }
  135. message.error(t('infra.messageNotProcessed') + data.value)
  136. } catch (error) {
  137. message.error(t('infra.anExceptionOccurredInProcessingTheMessage') + data.value)
  138. console.error(error)
  139. }
  140. })
  141. /** 发送消息 */
  142. const sendText = ref('') // 发送内容
  143. const sendUserId = ref('') // 发送人
  144. const handlerSend = () => {
  145. // 1.1 先 JSON 化 message 消息内容
  146. const messageContent = JSON.stringify({
  147. text: sendText.value,
  148. toUserId: sendUserId.value
  149. })
  150. // 1.2 再 JSON 化整个消息
  151. const jsonMessage = JSON.stringify({
  152. type: 'demo-message-send',
  153. content: messageContent
  154. })
  155. // 2. 最后发送消息
  156. send(jsonMessage)
  157. sendText.value = ''
  158. }
  159. /** 切换 websocket 连接状态 */
  160. const toggleConnectStatus = () => {
  161. if (getIsOpen.value) {
  162. close()
  163. } else {
  164. open()
  165. }
  166. }
  167. /** 初始化 **/
  168. const userList = ref<any[]>([]) // 用户列表
  169. onMounted(async () => {
  170. // 获取用户列表
  171. userList.value = await UserApi.getSimpleUserList()
  172. })
  173. </script>