wordpress如何设置网站地图,秦皇岛属于河北哪个市,网站建设基本要素,建设工程行业网站有哪些一、简介#xff08;什么是WebSocket#xff09; WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工#xff08;full-duplex#xff09;通信#xff0c;即允许服务器主动发送信息给客户端。因此#xff0c;在WebSocket中#xff0c;浏览器和服务…一、简介什么是WebSocket WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工full-duplex通信即允许服务器主动发送信息给客户端。因此在WebSocket中浏览器和服务器只需要完成一次握手两者之间就直接可以创建持久性的连接并进行双向数据传输客户端和服务器之间的数据交换变得更加简单。
二、数据实时推送的实现方式和应用场景 1.轮询 客户端通过代码定时向服务器发送AJAX请求,服务器接收请求并返回响应信息。优点代码相对简单,适用于小型应用。缺点在服务器数据没有更新时,会造成请求重复数据,请求无用,浪费带宽和服务器资源。2.长连接 在页面中嵌入一个隐藏的iframe,将这个隐藏的iframe的属性设置为一个长连接的请求或者xrh请求,服务器通过这种方式往客户端输入数据。优点数据实时刷新,请求不会浪费,管理较简洁。缺点长时间维护保持一个长连接会增加服务器开销。3.webSocket websocket是HTML5开始提供的一种客户端与服务器之间进行通讯的网络技术,通过这种方式可以实现客户端和服务器的长连接,双向实时通讯。优点减少资源消耗;实时推送不用等待客户端的请求;减少通信量;缺点少部分浏览器不支持不同浏览器支持的程度和方式都不同。 应用场景聊天室、智慧大屏、消息提醒、股票k线图监控等。三、代码实现 后端 1.pom.xml添加WebSocke依赖 org.springframework.boot spring-boot-starter-websocket 2.WebSocke配置类
Configuration
public class WebSocketConfig {/*** 这个bean的注册,用于扫描带有ServerEndpoint的注解成为websocket ,如果你使用外置的tomcat就 不需要该配置文件*/Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}3.WebSocke服务类
ServerEndpoint(value /webSocket)//主要是将目前的类定义成一个websocket服务器端, 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
Component
EnableScheduling// cron定时任务
Data
public class WebSocket {private static final Logger logger LoggerFactory.getLogger(WebSocket.class);/*** 静态变量用来记录当前在线连接数。应该把它设计成线程安全的。*/private static int onlineCount 0;/*** concurrent包的线程安全Set用来存放每个客户端对应的MyWebSocket对象。*/private static CopyOnWriteArraySetWebSocket webSocketSet new CopyOnWriteArraySet();/*** 与某个客户端的连接会话需要通过它来给客户端发送数据*/private Session session;public static CopyOnWriteArraySetWebSocket getWebSocketSet() {return webSocketSet;}public static void setWebSocketSet(CopyOnWriteArraySetWebSocket webSocketSet) {WebSocket.webSocketSet webSocketSet;}/*** 从数据库查询相关数据信息,可以根据实际业务场景进行修改*/Resourceprivate IndexService indexService;private static IndexService indexServiceMapper;PostConstructpublic void init() {WebSocket.indexServiceMapper this.indexService;}/*** 连接建立成功调用的方法** param session 会话*/OnOpenpublic void onOpen(Session session) throws Exception {this.session session;webSocketSet.add(this);//查询当前在线人数int nowOnline indexServiceMapper.nowOnline();this.sendMessage(JSON.toJSONString(nowOnline));}/*** 收到客户端消息后调用的方法** param message 客户端发送过来的消息*/OnMessagepublic void onMessage(String message, Session session) throws IOException {logger.info(参数信息{}, message);//群发消息for (WebSocket item : webSocketSet) {try {item.sendMessage(JSON.toJSONString(message));} catch (IOException e) {e.printStackTrace();}}}/*** 连接关闭调用的方法*/OnClosepublic void onClose() {webSocketSet.remove(this);if (session ! null) {try {session.close();} catch (IOException e) {e.printStackTrace();}}}/*** 发生错误时调用** param session 会话* param error 错误信息*/OnErrorpublic void onError(Session session, Throwable error) {logger.error(连接异常);error.printStackTrace();}/*** 发送信息** param message 消息*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/*** 自定义消息推送、可群发、单发** param message 消息*/public static void sendInfo(String message) throws IOException {logger.info(信息:{}, message);for (WebSocket item : webSocketSet) {item.sendMessage(message);}}
}4.定时任务为了给前端实时推送数据我这里写了个定时任务定时任务我用的是cron表达式,不懂的同学可以上这个网址学习cron表达式
Slf4j
Component
public class IndexScheduled {Autowiredprivate IndexMapper indexMapper;/*** 每3秒执行一次*///Scheduled(cron 0/3 * * * * ? ) //我这里暂时不需要运行这条定时任务所以将注解注释了朋友们运行时记得放开注释啊public void nowOnline() {System.err.println(********* 首页定时任务执行 **************);CopyOnWriteArraySetWebSocket webSocketSet WebSocket.getWebSocketSet();int nowOnline indexMapper.nowOnline();webSocketSet.forEach(c - {try {c.sendMessage(JSON.toJSONString(nowOnline));} catch (IOException e) {e.printStackTrace();}});System.err.println(/n 首页定时任务完成.......);}}前端 前端的代码非常的简单直接上代码。
body classgray-bgdiv classonlinespan classonline测试在线人数span idonline/spannbsp人/span
/divscript th:inlinejavascriptlet websocket null;let host document.location.host;//判断当前浏览器是否支持WebSocketif (WebSocket in window) {//连接WebSocket节点websocket new WebSocket(ws:// host /webSocket);} else {alert(浏览器不支持webSocket);}//连接发生错误的回调方法websocket.onerror function () {setMessageInnerHTML(error);};//连接成功建立的回调方法websocket.onopen function (event) {setMessageInnerHTML(open);};//接收到消息的回调方法websocket.onmessage function (event) {let data event.data;console.log(后端传递的数据: data);//将后端传递的数据渲染至页面$(#online).html(data);};//连接关闭的回调方法websocket.onclose function () {setMessageInnerHTML(close);};//监听窗口关闭事件当窗口关闭时主动去关闭websocket连接防止连接还没断开就关闭窗口server端会抛异常。window.onbeforeunload function () {websocket.close();};//将消息显示在网页上function setMessageInnerHTML(innerHTML) {};//关闭连接function closeWebSocket() {websocket.close();};//发送消息function send() {let message document.getElementById(text).value;websocket.send(message);};/script/body