vue实现stompjs+websocket和后端通信
<template>
<div>
<button @click="connect">连接</button>
<button @click="disconnect">断开连接</button>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script>
import SockJS from 'sockjs-client';
import Stomp from 'webstomp-client';
export default {
data() {
return {
stompClient: null,
};
},
methods: {
connect() {
const socket = new SockJS('http://localhost:8080/endpoint-websocket');
this.stompClient = Stomp.over(socket);
this.stompClient.connect({}, frame => {
console.log('Connected: ' + frame);
this.stompClient.subscribe('/topic/greetings', message => {
// 处理接收到的消息
console.log(JSON.parse(message.body).content);
});
});
},
disconnect() {
if (this.stompClient) {
this.stompClient.disconnect();
}
},
sendMessage() {
if (this.stompClient) {
const msg = { 'name': "John" };
this.stompClient.send('/app/hello', JSON.stringify(msg), {});
}
}
}
};
</script>
这个代码实例展示了如何在Vue.js应用中使用Stompjs和WebSocket建立连接、订阅消息、发送消息和断开连接。注意,这里假设你已经有一个运行的WebSocket服务端点,例如:http://localhost:8080/endpoint-websocket。同时,这个例子中的连接参数和订阅的目的地(例如:'/topic/greetings'和'/app/hello')需要根据实际的WebSocket服务进行相应的修改。
评论已关闭