websocket连接样例

This commit is contained in:
1378012178@qq.com 2025-11-07 15:12:51 +08:00
parent 424606b95c
commit 5edd47c1c9
1 changed files with 210 additions and 0 deletions

210
src/views/test/index.vue Normal file
View File

@ -0,0 +1,210 @@
<template>
<div class="websocket-test">
<h2>WebSocket 测试工具</h2>
<div class="connection-panel">
<el-input v-model="userId" placeholder="输入用户ID" style="width: 200px"></el-input>
<el-button type="primary" @click="connect" :disabled="isConnected">连接</el-button>
<el-button type="danger" @click="disconnect" :disabled="!isConnected">断开</el-button>
<el-button @click="sendPing" :disabled="!isConnected">发送心跳</el-button>
<span class="status" :class="{ connected: isConnected }">
{{ isConnected ? '已连接' : '未连接' }}
</span>
</div>
<div class="message-panel">
<el-input v-model="messageToSend" placeholder="输入要发送的消息"
style="width: 300px; margin-right: 10px"></el-input>
<el-button type="primary" @click="sendMessage" :disabled="!isConnected">发送</el-button>
</div>
<div class="log-panel">
<h3>消息日志</h3>
<div class="log-content">
<div v-for="(log, index) in logs" :key="index" class="log-item">
<span class="log-time">[{{ log.time }}]</span>
<span class="log-message">{{ log.message }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'WebSocketTest',
data() {
return {
token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NjI3MTg2MTUsInVzZXJuYW1lIjoiYWRtaW4ifQ.qSwjclSvEHOefAjm9Oqay9dmhLUZy1cgIBeE1u1Twg8',
userId: 'test_user_' + Math.floor(Math.random() * 1000), // ID
ws: null,
isConnected: false,
messageToSend: '',
logs: [],
reconnectAttempts: 0,
maxReconnectAttempts: 5,
reconnectDelay: 5000 // 5
}
},
methods: {
connect() {
if (this.isConnected) return
// WebSocket
const wsUrl = `ws://localhost:8091/nursing-unit_101/directive/websocket/${this.userId}?token=${this.token}`
this.ws = new WebSocket(wsUrl)
this.ws.onopen = () => {
this.isConnected = true
this.reconnectAttempts = 0
this.addLog('连接成功')
//
this.startHeartbeat()
}
this.ws.onmessage = (event) => {
const message = event.data
this.addLog(`收到消息: ${message}`)
//
if (message === 'pong') {
this.addLog('收到心跳响应')
}
}
this.ws.onclose = () => {
this.isConnected = false
this.addLog('连接已关闭')
//
this.stopHeartbeat()
//
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++
this.addLog(`将在 ${this.reconnectDelay / 1000} 秒后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
setTimeout(() => {
this.connect()
}, this.reconnectDelay)
}
}
this.ws.onerror = (error) => {
this.addLog(`连接错误: ${error.message || '未知错误'}`)
}
},
disconnect() {
if (this.ws) {
this.ws.close()
this.ws = null
}
this.isConnected = false
this.stopHeartbeat()
},
sendMessage() {
if (this.ws && this.isConnected) {
this.ws.send(this.messageToSend)
this.addLog(`发送消息: ${this.messageToSend}`)
this.messageToSend = ''
}
},
sendPing() {
if (this.ws && this.isConnected) {
this.ws.send('ping')
this.addLog('发送心跳: ping')
}
},
startHeartbeat() {
// 30
this.heartbeatInterval = setInterval(() => {
if (this.isConnected) {
this.sendPing()
}
}, 30000)
},
stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval)
this.heartbeatInterval = null
}
},
addLog(message) {
const time = new Date().toLocaleTimeString()
this.logs.unshift({ time, message })
if (this.logs.length > 100) {
this.logs.pop()
}
}
},
beforeDestroy() {
this.disconnect()
}
}
</script>
<style scoped>
.websocket-test {
padding: 20px;
max-width: 800px;
margin: 0 auto;
}
.connection-panel {
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 10px;
}
.status {
margin-left: 10px;
padding: 5px 10px;
border-radius: 4px;
background-color: #f56c6c;
color: white;
}
.status.connected {
background-color: #67c23a;
}
.message-panel {
margin-bottom: 20px;
display: flex;
align-items: center;
}
.log-panel {
border: 1px solid #ebeef5;
border-radius: 4px;
padding: 15px;
}
.log-content {
max-height: 400px;
overflow-y: auto;
}
.log-item {
padding: 5px 0;
border-bottom: 1px dashed #ebeef5;
}
.log-time {
color: #909399;
margin-right: 10px;
}
.log-message {
word-break: break-all;
}
</style>