SpringBoot初探WebSocket
文章目录
HTTP协议单向的,客户端发起请求,服务端返回结果。 类似于看电视,你选择电台,看不同的节目。
WebSocket最大的有点就是双向的, 类似于微博,微信等,双方可以互动。服务端也可以给客户端发送消息,实现公平对话。
用SpringBoot搭建WebSocket
1. 新建SpringBoot项目,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 新建一个Java配置类,即用@Configuration修饰的类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
注入 ServerEndpointExporter 配置,如果是使用 springboot 内置的 tomcat 此配置必须,如果是使用的是外部 tomcat 容器此步骤请忽略。看 spring 源码中这样描述,使用此配置可以关闭 servlet 容器对 websocket 端点的扫描,这个暂时没有深入研究。
3. 后端类的编写
3.1 核心类的编写
简单介绍下WebSocket的几个事件注解,引入上面的pom依赖后,可以方便的引用这几个事件注解
- @OnOpen() : 建立连接触发
- @OnMessage() : 发送消息触发
- @OnClose() : 关闭连接,或者前端页面触发
@ServerEndpoint(value = "/wsdemo") //url,访问的时候就是 localhost+端口号+/wsdemo
@Component //交给Spring管理
public class MyWebSocket {
private static int onlineCount = 0; //会话总数
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
private Session session;
@OnOpen //连接建立触发,可以在里面做些业务操作
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
System.out.println("有新连接加入! 当前在线人数为" + getOnlineCount());
try {
sendMessage("连接已建立");
} catch (Exception e) {
System.out.println("IO异常");
}
}
@OnClose //连接关闭触发
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage //前端页面发消息触发
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public static CopyOnWriteArraySet<MyWebSocket> getWebSocketSet() {
return webSocketSet;
}
public static void setWebSocketSet(CopyOnWriteArraySet<MyWebSocket> webSocketSet) {
MyWebSocket.webSocketSet = webSocketSet;
}
}
简单了解下
CopyOnWriteArraySet
底层是用集合实现,线程安全,不可重复
3.2 定时任务
定时发送消息
@Component
public class TimeTask {
private static Logger logger = LoggerFactory.getLogger(TimeTask.class);
@Scheduled( cron = "0/1 * * * * ?")
public void test() {
System.err.println("************ 定时任务执行 ***********");
CopyOnWriteArraySet<MyWebSocket> webSocketSet = MyWebSocket.getWebSocketSet();
int i = 0;
webSocketSet.forEach(c ->{
try {
c.sendMessage(" 定时发送 " + new Date().toLocaleString());
} catch (IOException e) {
e.printStackTrace();
}
});
System.err.println("************ 定时任务完成 ***********");
}
}
4. 前端页面
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome
<br/>
<input type="text" id="text"/>
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket ,主要此处要更换为自己的地址
if ('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/wsdemo");
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function (){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function (){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
// document.getElementById('message') += innerHTML + '<br/>';
// document.getElementById('message').innerHTML += innerHTML;
console.log(innerHTML);
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
5. 运行效果图
每次新开一个页面
上面是访客端输入框,下面是定时任务回复的内容,每隔一秒发送一次
后端页面日志
开启一个页面
发送一条消息