WebSocket
1.背景
为了实现推送技术,实时更新前端页面。
2.实现方式
1.Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器
2.浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
3.优势
Ajax:这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
webSocket:HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
4.SpringBoot整合webSocket 的DEMO
源码git地址:https://gitee.com/x_p_fei/boot-web-socket.git
1.引入依赖pom.xml
<!--websocket连接需要使用到的包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
2.注入ServerEndpointExporter
新建文件WebSocketConfig.java@ConfigurationpublicclassWebSocketConfig{@Beanpublic ServerEndpointExporterserverEndpointExporter(){returnnewServerEndpointExporter();}
3.webSocket服务文件
package cn.sr.nrsd.webSocket.socket;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.concurrent.CopyOnWriteArrayList;@Slf4j@ServerEndpoint("/websocket")@ComponentpublicclassWebSocketController{privatestaticint onlineCount=0;privatestatic CopyOnWriteArrayList<WebSocketController> webSocketSet=newCopyOnWriteArrayList<WebSocketController>();private Session session;@OnOpenpublicvoidonOpen(Session session){this.session= session;
webSocketSet.add(this);//加入set中addOnlineCount();
System.out.println("有新连接加入!当前在线人数为"+getOnlineCount());}@OnClosepublicvoidonClose(){
webSocketSet.remove(this);subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为"+getOnlineCount());}@OnMessagepublicvoidonMessage(String message, Session session){
System.out.println("来自客户端的消息:"+ message);// 群发消息try{sendMessage(message);}catch(IOException e){
e.printStackTrace();}}@OnErrorpublicvoidonError(Session session, Throwable throwable){
System.out.println("发生错误!");
throwable.printStackTrace();}// 下面是自定义的一些方法publicvoidsendMessage(String message)throws IOException{for(WebSocketController webSocketController: webSocketSet){try{
Session toSession= webSocketController.session;if(toSession.isOpen()){
log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
toSession.getAsyncRemote().sendText(message);}}catch(Exception e){
e.printStackTrace();continue;}}}publicstaticsynchronizedintgetOnlineCount(){return onlineCount;}publicstaticsynchronizedvoidaddOnlineCount(){
WebSocketController.onlineCount++;}publicstaticsynchronizedvoidsubOnlineCount(){
WebSocketController.onlineCount--;}}
4.添加静态页面
在项目resources下面新建文件 static, 在static文件中添加静态页面index.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Java后端WebSocket的Tomcat实现</title></head><body>
Welcome<br/><inputid="text"type="text"/><buttononclick="send()">发送消息</button><hr/><buttononclick="closeWebSocket()">关闭WebSocket连接</button><hr/><divid="message"></div></body><scripttype="text/javascript">var websocket=null;//判断当前浏览器是否支持WebSocketif('WebSocket'in window){//注意修改端口号
websocket=newWebSocket('ws://localhost:7001/websocket');}else{alert('当前浏览器 Not support websocket')}//连接发生错误的回调方法
websocket.onerror=function(){setMessageInnerHTML("WebSocket连接发生错误");};//连接成功建立的回调方法
websocket.onopen=function(){setMessageInnerHTML("WebSocket连接成功");}//接收到消息的回调方法
websocket.onmessage=function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法
websocket.onclose=function(){setMessageInnerHTML("WebSocket连接关闭");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload=function(){closeWebSocket();}//将消息显示在网页上functionsetMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML+= innerHTML+'<br/>';}//关闭WebSocket连接functioncloseWebSocket(){
websocket.close();}//发送消息functionsend(){var message= document.getElementById('text').value;
websocket.send(message);}</script></html>
5.启动失败原因
AOP日志切面,切到了webSocket服务,导致@ServerEndpoint没有注入,启动报错。注意修改切面日志或者包名,不要被AOP扫描到。 ——>启动成功
6.启动项目
访问 localhost:7001/,会跳转到 index 页面。然后可以进行发消息操作。
点击发消息,前端先把消息传到服务器,之后服务器处理后再发送给前端。服务器也可以直接发送消息到前端页面。至此就实现了后端服务器推送技术。