Vue 通过@stomp/stompjs建立长链接 无法进入connect回调
<template>
<div>
<h1>WebSocket 长连接示例</h1>
<button @click="startConnection">开始连接</button>
<button @click="stopSubscription" :disabled="!isConnected">取消订阅</button>
<button @click="closeConnection" :disabled="!isConnected">关闭连接</button>
<input v-model="messageToSend" placeholder="输入消息">
<button @click="sendMessage" :disabled="!isConnected">发送消息</button>
<div v-if="receivedMessage">
<h2>收到的消息:</h2>
<p>{{ receivedMessage }}</p>
</div>
</div>
</template>
<script>
import { Stomp } from '@stomp/stompjs';
export default {
data() {
return {
client: null,
subscription: null,
url: 'ws://127.0.0.1:9000',
topic: '/topic/test',
customHeaders: {},
isConnected: false,
receivedMessage: null,
messageToSend: '',
};
},
methods: {
startConnection() {
console.log('尝试连接到', this.url);
this.client = Stomp.client(this.url);
this.client.configure({
connectHeaders: this.customHeaders,
heartbeatIncoming: 10,
heartbeatOutgoing: 20,
onConnect: (frame) => {
console.log('连接成功', frame);
this.isConnected = true;
this.subscription = this.client.subscribe(this.topic, (message) => {
console.log('收到消息', message.body);
this.receivedMessage = message.body;
});
},
onStompError: (error) => {
console.error('STOMP 错误', error);
this.handleConnectionError(error);
},
onWebSocketClose: (event) => {
console.error('连接关闭', event);
this.isConnected = false;
},
onWebSocketError: (event) => {
console.error('WebSocket 错误', event);
this.handleConnectionError(event);
},
debug: (str) => {
console.log('+++++ DEBUG +++++');
console.log(new Date(), str);
}
});
this.client.activate();
},
stopSubscription() {
if (this.subscription) {
this.subscription.unsubscribe();
console.log('取消订阅');
}
},
closeConnection() {
if (this.client && this.isConnected) {
this.client.deactivate(() => {
console.log('关闭连接');
this.isConnected = false;
});
}
},
sendMessage() {
if (this.client && this.isConnected) {
const message = { text: this.messageToSend };
this.client.publish({ destination: this.topic, body: JSON.stringify(message) });
console.log('消息已发送', message);
} else {
console.log('WebSocket 未连接');
}
},
handleConnectionError(error) {
console.error('WebSocket 连接错误', error);
this.isConnected = false;
}
},
};
</script>
<style scoped>
button {
margin: 10px;
}
input {
margin: 10px;
}
</style>
const WebSocket = require('ws');
// 指定自定义端口号
const PORT = 9000;
const server = new WebSocket.Server({ port: PORT });
server.on('connection', (ws) => {
console.log('客户端已连接');
ws.on('message', (message) => {
console.log(`收到消息: ${message}`);
// 发送响应消息
ws.send(`服务器收到: ${message}`);
});
ws.on('close', () => {
console.log('客户端已断开连接');
});
ws.on('error', (error) => {
console.log(`WebSocket 错误: ${error}`);
});
});
console.log(`WebSocket 服务器在 ws://localhost:${PORT} 运行`);
如上分别为前后端代码 点击开始链接 启动后端ws服务 后端控制台提示客户端已连接,但是前端onConnect回调一直无法进入 ,只有debug事件回调正常
目前不确定是否真正建立了链接 希望获取onConnect的回调事件
是版本不同的缘故么,看着跟官方示例不太一样
https://github.com/stomp-js/stompjs