简易集成websocket技术实现消息推送

时间:2023-03-09 05:55:24
简易集成websocket技术实现消息推送

Websocket

简介

首先介绍下WebSocket,它是一种网络通信技术,该技术最大的特点就是,服务器端可以主动往客户端发送消息;当然,客户端也可以主动往服务器发送消息,实现两端的消息通信,属于网络推送消息技术的一种。

好处

为什么我们需要websocket这门技术呢,通常情况下,我们要想实现类似于消息通知的功能,得主动刷新才能知道是否有新的消息?这样的话,就显得我们的项目很笨重,不灵活。集成了websocket技术的话,消息就能实时刷新,这样对于一些类似于文章点赞,评论等这些实时消息,用户体验感会大大提高。

话不多说,下面看下代码实现

代码实现

pom.xml
首先先添加websocket的依赖(这是spring的)

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>

SpringBoot的如下

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置层

@Component
public class WebSocketConfig { @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

业务层

@Component
@ServerEndpoint("/webSocket")
public class WebSocket { private Session session; // 定义websocket的容器,储存session
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); // 对应前端写的事件
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this);
System.out.println("【websocket消息】有新的连接进来了,目标数:"+ webSocketSet.size());
} @OnClose
public void onClose() {
webSocketSet.remove(this);
System.out.println("【websocket消息】有连接断开了,目标数为:"+ webSocketSet.size());
} @OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端发送过来的消息:" + message);
} public void sendMessage(String message){
for (WebSocket webSocket : webSocketSet){
System.out.println("【websocket消息】广播消息,message="+ message);
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e){
e.printStackTrace();
}
}
} }

controller层

@Autowired
private WebSocket websocket;
// 在你发送消息(或者实现相关功能的地方)
// 调用websocket的sendMessage方法,将内容代入方法体
websocket.sendMessage("消息内容");

前端页面层

   //	websocket消息通知
var websocket = null;
// 判断浏览器是否支持websocket技术
if('WebSocket' in window) {
websocket = new WebSocket('ws://127.0.0.1:8080/webSocket');
}else {
alert('抱歉,您的浏览器不支持websocket!')
} websocket.onopen = function (event) {
console.log('建立连接成功')
} websocket.onclose = function (event) {
console.log('连接已经关闭')
} websocket.onmessage = function (event) {
console.log('收到消息:' + event.data)
} websocket.onerror = function (event) {
console.log('websocket消息通信发生错误!')
}
// 窗口关闭,websocket也就关闭
window.onbeforeunload = function () {
websocket.close();
}