websocket基础Demo------>在项目中实际使用
- 后端springboot本身就集成了websocket,只需要自己手写一个websocket类(包含端口、接客户端发送的信息、向客户端发送广播、单点信息等),重点是给客户端发送的信息的处理
- 前端Vue也同样需要一个类似后端websokcet类的一个对象
new WebSocket('ws://localhost:8081/websocket/trend')(包含连接服务器端口、接收服务端数据并通过回调函数发送给相应的组件、向服务端发送数据、),
服务端代码springboot
导入springboot-webcoket启动类的pom
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
websokcet的服务类(核心):其中的CharServiceUtils是自己手写的工具类,主要实现信息的封装成Json返回,其中有无法导入service层、mapper层的坑,已解决
/**
* 相当于后端请求的websocket连接端口,之后调用sendTextMessage等方法向前端发送数据
*/
@Component
@ServerEndpoint("/websocket/{chartId}")
//此注解相当于设置访问URL
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
@OnOpen
public void onOpen(Session session, @PathParam(value="chartId")String chartId) {
this.session = session;
webSockets.add(this);
sessionPool.put(chartId, session);
System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
Message msg = JSON.parseObject(message, Message.class);
switch (msg.getAction()){
case "getData":
msg.setValue(CharServiceUtils.getchartData(msg.getChartName()));
sendAllMessage(JsonUtils.getJson(msg));
break;
case "fullScreen":
msg.setValue(CharServiceUtils.getchartData("count"));
sendAllMessage(JsonUtils.getJson(msg));
break;
case "themeChange":break;
}
}
// 此为广播消息
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息 (发送文本)
public void sendTextMessage(String chartId, String message) {
Session session = sessionPool.get(chartId);
if (session != null) {
try {
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息 (发送对象)
public void sendObjMessage(String chartId, Object message) {
Session session = sessionPool.get(chartId);
if (session != null) {
try {
session.getAsyncRemote().sendObject(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
客户端代码vue设计
主要功能:创建websokcet对象连接服务器端端口、向服务器端发送数据、接收服务端数据并通过回调函数发送给相应的组件
设计流程:
1.定义单例,创建 WebSocket实例对象
- 创建 src/utils/socket_service.js 文件
- 定义单例
export default class SocketService {
/**
* 单例
*/
static instance = null;

本文详细介绍了如何在SpringBoot后端和Vue前端实现WebSocket的集成,包括后端配置WebSocket启动依赖,创建WebSocket服务类处理各种事件,前端创建WebSocket对象连接服务器,监听并处理服务器消息。此外,还涉及到了错误处理、广播和单点消息的发送、数据的解析和回调函数的注册。整个流程涵盖了WebSocket连接的建立、数据交互以及断开重连机制。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



