index.vue 5.4 KB

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