WebSocket前端SockJS获取订阅的信息文本内容
一. 引入SockJS依赖
1. vue引入依赖
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
2. maven引入依赖
pom.xml
文件添加依赖
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
- html文件里引入jar包的js
<script src="/webjars/sockjs-client/1.0.2/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/2.3.3/stomp.min.js"></script>
注意: 使用maven引入依赖的项目springboot
二. 创建连接, 订阅消息
var socket = new SockJS('/wsdemo');
stompClient = Stomp.over(socket);
// 创建连接
stompClient.connect({}, function (frame) {
//订阅消息
stompClient.subscribe('/topic/message', function (data) {
initOnLine(data.body)
});
);
三. 获取订阅的消息
//订阅消息
stompClient.subscribe('/topic/message', (msg) => {
// 输出返回的信息
console.log(msg);
// 输出返回的消息的文本内容
console.log(meg.body);
});
---- ## 参考来源 [vue使用SockJS实现webSocket通信](https://www.cnblogs.com/luoxuemei/p/10115679.html)