index.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <template>
  2. <view class="min-h-screen bg-[#f5f5f5]">
  3. <!-- 顶部导航栏 -->
  4. <wd-navbar
  5. title="WebSocket 测试"
  6. left-arrow placeholder safe-area-inset-top fixed
  7. @click-left="handleBack"
  8. />
  9. <!-- 连接状态卡片 -->
  10. <view class="mx-24rpx mt-24rpx overflow-hidden rounded-16rpx bg-white shadow-sm">
  11. <view class="p-32rpx">
  12. <!-- 状态指示器 -->
  13. <view class="mb-24rpx flex items-center">
  14. <view
  15. class="mr-16rpx h-20rpx w-20rpx rounded-full"
  16. :class="isConnected ? 'bg-[#07c160]' : 'bg-[#fa5151]'"
  17. />
  18. <text class="text-32rpx text-[#333] font-semibold">连接管理</text>
  19. </view>
  20. <!-- 连接状态 -->
  21. <view class="mb-24rpx flex items-center rounded-12rpx bg-[#f7f8fa] p-24rpx">
  22. <text class="mr-16rpx text-28rpx text-[#666]">连接状态:</text>
  23. <wd-tag :type="isConnected ? 'success' : 'danger'">
  24. {{ statusText }}
  25. </wd-tag>
  26. </view>
  27. <!-- 服务地址 -->
  28. <view class="mb-24rpx">
  29. <text class="mb-12rpx block text-26rpx text-[#999]">服务地址</text>
  30. <view class="rounded-12rpx bg-[#f7f8fa] p-24rpx">
  31. <text class="break-all text-26rpx text-[#666]">{{ serverUrl }}</text>
  32. </view>
  33. </view>
  34. <!-- 连接按钮 -->
  35. <wd-button
  36. block
  37. :type="isConnected ? 'error' : 'primary'"
  38. @click="toggleConnection"
  39. >
  40. {{ isConnected ? '断开连接' : '建立连接' }}
  41. </wd-button>
  42. </view>
  43. </view>
  44. <!-- 发送消息卡片 -->
  45. <view class="mx-24rpx mt-24rpx overflow-hidden rounded-16rpx bg-white shadow-sm">
  46. <view class="p-32rpx">
  47. <view class="mb-24rpx flex items-center">
  48. <wd-icon name="chat" size="36rpx" color="#1989fa" class="mr-12rpx" />
  49. <text class="text-32rpx text-[#333] font-semibold">发送消息</text>
  50. </view>
  51. <!-- 接收人选择 -->
  52. <view class="mb-24rpx">
  53. <text class="mb-12rpx block text-26rpx text-[#999]">接收人</text>
  54. <wd-picker
  55. v-model="sendUserId"
  56. :columns="userColumns"
  57. :disabled="!isConnected"
  58. @confirm="handleUserChange"
  59. >
  60. <view class="flex items-center justify-between rounded-12rpx bg-[#f7f8fa] p-24rpx">
  61. <text class="text-28rpx" :class="isConnected ? 'text-[#333]' : 'text-[#c8c9cc]'">
  62. {{ selectedUserLabel }}
  63. </text>
  64. <wd-icon name="arrow-down" size="32rpx" :color="isConnected ? '#666' : '#c8c9cc'" />
  65. </view>
  66. </wd-picker>
  67. </view>
  68. <!-- 消息内容 -->
  69. <view class="mb-24rpx">
  70. <text class="mb-12rpx block text-26rpx text-[#999]">消息内容</text>
  71. <wd-textarea
  72. v-model="sendText"
  73. placeholder="请输入要发送的消息..."
  74. :disabled="!isConnected"
  75. :maxlength="500"
  76. show-word-limit
  77. auto-height
  78. :min-height="120"
  79. />
  80. </view>
  81. <!-- 发送按钮 -->
  82. <wd-button
  83. block
  84. type="primary"
  85. :disabled="!isConnected || !sendText.trim()"
  86. @click="handleSend"
  87. >
  88. <wd-icon name="send" size="32rpx" class="mr-8rpx" />
  89. 发送消息
  90. </wd-button>
  91. </view>
  92. </view>
  93. <!-- 消息记录卡片 -->
  94. <view class="mx-24rpx mb-24rpx mt-24rpx overflow-hidden rounded-16rpx bg-white shadow-sm">
  95. <view class="p-32rpx">
  96. <view class="mb-24rpx flex items-center justify-between">
  97. <view class="flex items-center">
  98. <wd-icon name="list" size="36rpx" color="#1989fa" class="mr-12rpx" />
  99. <text class="text-32rpx text-[#333] font-semibold">消息记录</text>
  100. <wd-tag v-if="messageList.length > 0" type="primary" plain class="ml-16rpx">
  101. {{ messageList.length }} 条
  102. </wd-tag>
  103. </view>
  104. <wd-button
  105. v-if="messageList.length > 0"
  106. size="small"
  107. type="error"
  108. plain
  109. @click="clearMessages"
  110. >
  111. 清空
  112. </wd-button>
  113. </view>
  114. <!-- 消息列表 -->
  115. <scroll-view
  116. scroll-y
  117. class="message-list rounded-12rpx bg-[#f7f8fa]"
  118. :style="{ height: '600rpx' }"
  119. >
  120. <view v-if="messageList.length === 0" class="h-full flex flex-col items-center justify-center">
  121. <wd-icon name="inbox" size="80rpx" color="#c8c9cc" />
  122. <text class="mt-16rpx text-26rpx text-[#c8c9cc]">暂无消息记录</text>
  123. </view>
  124. <view v-else class="p-20rpx">
  125. <view
  126. v-for="(msg, index) in messageReverseList"
  127. :key="index"
  128. class="mb-20rpx rounded-12rpx bg-white p-24rpx shadow-sm"
  129. >
  130. <view class="mb-12rpx flex items-center justify-between">
  131. <view class="flex items-center">
  132. <view
  133. class="mr-12rpx h-16rpx w-16rpx rounded-full"
  134. :style="{ backgroundColor: getMessageBadgeColor(msg.type) }"
  135. />
  136. <text class="text-26rpx text-[#666] font-medium">
  137. {{ getMessageTypeText(msg.type) }}
  138. </text>
  139. <text v-if="msg.userId" class="ml-16rpx text-24rpx text-[#999]">
  140. 用户 ID: {{ msg.userId }}
  141. </text>
  142. </view>
  143. <text class="text-22rpx text-[#c8c9cc]">
  144. {{ formatDateTime(msg.time) }}
  145. </text>
  146. </view>
  147. <view class="break-words text-28rpx text-[#333]">
  148. {{ msg.text }}
  149. </view>
  150. </view>
  151. </view>
  152. </scroll-view>
  153. </view>
  154. </view>
  155. <!-- 底部安全区域 -->
  156. <view class="h-env(safe-area-inset-bottom)" />
  157. </view>
  158. </template>
  159. <script lang="ts" setup>
  160. import type { User } from '@/api/system/user'
  161. import { computed, onMounted, onUnmounted, ref } from 'vue'
  162. import { getSimpleUserList } from '@/api/system/user'
  163. import { useTokenStore } from '@/store/token'
  164. import { getEnvBaseUrlRoot } from '@/utils'
  165. import { formatDateTime } from '@/utils/date'
  166. definePage({
  167. style: {
  168. navigationBarTitleText: '',
  169. navigationStyle: 'custom',
  170. },
  171. })
  172. // ======================= 状态定义 =======================
  173. const tokenStore = useTokenStore()
  174. // WebSocket 相关状态
  175. const socketTask = ref<UniApp.SocketTask | null>(null)
  176. const isConnected = ref(false)
  177. const statusText = computed(() => (isConnected.value ? '已连接' : '未连接'))
  178. // 服务地址
  179. const serverUrl = computed(() => {
  180. const baseUrl = getEnvBaseUrlRoot()
  181. const wsUrl = baseUrl.replace('http', 'ws')
  182. const tokenInfo = tokenStore.tokenInfo as any
  183. const token = tokenInfo?.refreshToken || tokenStore.validToken
  184. return `${wsUrl}/infra/ws?token=${token}`
  185. })
  186. // 消息相关状态
  187. interface Message {
  188. text: string
  189. time: number
  190. type?: 'single' | 'group' | 'system'
  191. userId?: string
  192. }
  193. const messageList = ref<Message[]>([])
  194. const messageReverseList = computed(() => [...messageList.value].reverse())
  195. // 发送消息相关
  196. const sendText = ref('')
  197. const sendUserId = ref('all')
  198. const userList = ref<User[]>([])
  199. const userColumns = computed(() => {
  200. const list = [
  201. { value: 'all', label: '所有人' },
  202. ...userList.value.map(user => ({
  203. value: String(user.id),
  204. label: user.nickname || user.username,
  205. })),
  206. ]
  207. return [list]
  208. }) // 用户选择器列表
  209. const selectedUserLabel = computed(() => {
  210. if (sendUserId.value === 'all') {
  211. return '所有人'
  212. }
  213. const user = userList.value.find(u => String(u.id) === sendUserId.value)
  214. return user?.nickname || user?.username || '所有人'
  215. }) // 选中的用户标签
  216. // ======================= WebSocket 方法 =======================
  217. /** 建立 WebSocket 连接 */
  218. function connect() {
  219. if (socketTask.value) {
  220. return
  221. }
  222. // 1.1 发起连接请求
  223. socketTask.value = uni.connectSocket({
  224. url: serverUrl.value,
  225. success: () => {
  226. console.log('WebSocket 连接请求已发送')
  227. },
  228. fail: (err) => {
  229. console.error('WebSocket 连接失败:', err)
  230. uni.showToast({ title: '连接失败', icon: 'error' })
  231. },
  232. })
  233. // 1.2 监听连接打开
  234. socketTask.value.onOpen(() => {
  235. console.log('WebSocket 连接已打开')
  236. isConnected.value = true
  237. uni.showToast({ title: '连接成功', icon: 'success' })
  238. // 开始心跳
  239. startHeartbeat()
  240. })
  241. // 2. 监听消息
  242. socketTask.value.onMessage((res) => {
  243. handleMessage(res.data as string)
  244. })
  245. // 3.1 监听连接关闭
  246. socketTask.value.onClose(() => {
  247. console.log('WebSocket 连接已关闭')
  248. isConnected.value = false
  249. socketTask.value = null
  250. stopHeartbeat()
  251. })
  252. // 3.2 监听错误
  253. socketTask.value.onError((err) => {
  254. console.error('WebSocket 错误:', err)
  255. isConnected.value = false
  256. socketTask.value = null
  257. stopHeartbeat()
  258. uni.showToast({ title: '连接异常', icon: 'error' })
  259. })
  260. }
  261. /** 关闭 WebSocket 连接 */
  262. function disconnect() {
  263. if (!socketTask.value) {
  264. return
  265. }
  266. socketTask.value.close({
  267. success: () => {
  268. console.log('WebSocket 连接已主动关闭')
  269. uni.showToast({ title: '已断开', icon: 'success' })
  270. },
  271. })
  272. socketTask.value = null
  273. isConnected.value = false
  274. stopHeartbeat()
  275. }
  276. /** 切换连接状态 */
  277. function toggleConnection() {
  278. if (isConnected.value) {
  279. disconnect()
  280. } else {
  281. connect()
  282. }
  283. }
  284. // ======================= 心跳机制 =======================
  285. let heartbeatTimer: ReturnType<typeof setInterval> | null = null
  286. /** 启动心跳机制 */
  287. function startHeartbeat() {
  288. stopHeartbeat()
  289. // 30 秒发送一次心跳
  290. heartbeatTimer = setInterval(() => {
  291. if (socketTask.value && isConnected.value) {
  292. socketTask.value.send({
  293. data: 'ping',
  294. fail: (err) => {
  295. console.error('心跳发送失败:', err)
  296. },
  297. })
  298. }
  299. }, 30000)
  300. }
  301. /** 停止心跳机制 */
  302. function stopHeartbeat() {
  303. if (heartbeatTimer) {
  304. clearInterval(heartbeatTimer)
  305. heartbeatTimer = null
  306. }
  307. }
  308. // ======================= 消息处理 =======================
  309. /** 处理接收到的消息 */
  310. function handleMessage(data: string) {
  311. if (!data) {
  312. return
  313. }
  314. try {
  315. // 心跳响应
  316. if (data === 'pong') {
  317. return
  318. }
  319. // 1. 解析消息
  320. const jsonMessage = JSON.parse(data)
  321. const type = jsonMessage.type
  322. const content = JSON.parse(jsonMessage.content)
  323. if (!type) {
  324. console.warn('未知的消息类型:', data)
  325. return
  326. }
  327. // 2.1 处理 demo-message-receive 消息
  328. if (type === 'demo-message-receive') {
  329. const single = content.single
  330. messageList.value.push({
  331. text: content.text,
  332. time: Date.now(),
  333. type: single ? 'single' : 'group',
  334. userId: content.fromUserId,
  335. })
  336. return
  337. }
  338. // 2.2 处理 notice-push 消息
  339. if (type === 'notice-push') {
  340. messageList.value.push({
  341. text: content.title,
  342. time: Date.now(),
  343. type: 'system',
  344. })
  345. return
  346. }
  347. console.warn('未处理的消息类型:', type, data)
  348. } catch (error) {
  349. console.error('消息解析失败:', error, data)
  350. }
  351. }
  352. /** 发送消息 */
  353. function handleSend() {
  354. if (!sendText.value.trim()) {
  355. uni.showToast({ title: '请输入消息内容', icon: 'none' })
  356. return
  357. }
  358. if (!socketTask.value || !isConnected.value) {
  359. uni.showToast({ title: '请先建立连接', icon: 'none' })
  360. return
  361. }
  362. // 1.1 构建消息内容
  363. const messageContent = JSON.stringify({
  364. text: sendText.value,
  365. toUserId: sendUserId.value === 'all' ? undefined : sendUserId.value,
  366. })
  367. // 1.2 构建完整消息
  368. const jsonMessage = JSON.stringify({
  369. type: 'demo-message-send',
  370. content: messageContent,
  371. })
  372. // 2. 发送消息
  373. socketTask.value.send({
  374. data: jsonMessage,
  375. success: () => {
  376. uni.showToast({ title: '发送成功', icon: 'success' })
  377. sendText.value = ''
  378. },
  379. fail: (err) => {
  380. console.error('消息发送失败:', err)
  381. uni.showToast({ title: '发送失败', icon: 'error' })
  382. },
  383. })
  384. }
  385. /** 清空消息记录 */
  386. function clearMessages() {
  387. messageList.value = []
  388. }
  389. // ======================= 工具方法 =======================
  390. /** 获取消息类型的徽标颜色 */
  391. function getMessageBadgeColor(type?: string) {
  392. switch (type) {
  393. case 'group':
  394. return '#07c160'
  395. case 'single':
  396. return '#1989fa'
  397. case 'system':
  398. return '#fa5151'
  399. default:
  400. return '#c8c9cc'
  401. }
  402. }
  403. /** 获取消息类型的文本 */
  404. function getMessageTypeText(type?: string) {
  405. switch (type) {
  406. case 'group':
  407. return '群发'
  408. case 'single':
  409. return '单发'
  410. case 'system':
  411. return '系统'
  412. default:
  413. return '未知'
  414. }
  415. }
  416. /** 处理用户选择变化 */
  417. function handleUserChange({ value }: { value: string[] }) {
  418. sendUserId.value = value[0] || 'all'
  419. }
  420. /** 返回上一页 */
  421. function handleBack() {
  422. uni.navigateBack()
  423. }
  424. // ======================= 生命周期 =======================
  425. /** 初始化 */
  426. onMounted(async () => {
  427. // 获取用户列表
  428. try {
  429. userList.value = await getSimpleUserList()
  430. }
  431. catch (error) {
  432. console.error('获取用户列表失败:', error)
  433. }
  434. })
  435. /** 页面卸载 */
  436. onUnmounted(() => {
  437. // 页面销毁时断开连接
  438. disconnect()
  439. })
  440. </script>
  441. <style lang="scss" scoped>
  442. .message-list {
  443. &::-webkit-scrollbar {
  444. display: none;
  445. }
  446. }
  447. </style>