网站开发所需费用支出有哪些,wordpress文章 插件,北京网站优化推广分析,可以发广告的100个网站一、概述
1.1 简介
WebSocket是HTML5下一种新的协议#xff08;websocket协议本质上是一个基于tcp的协议#xff09;#xff0c;它实现了浏览器与服务器全双工通信#xff0c;能更好的节省服务器资源和带宽并达到实时通讯的目的#xff0c;Websocket是一个持久化的协议。…一、概述
1.1 简介
WebSocket是HTML5下一种新的协议websocket协议本质上是一个基于tcp的协议它实现了浏览器与服务器全双工通信能更好的节省服务器资源和带宽并达到实时通讯的目的Websocket是一个持久化的协议。
1.2 原理
websocket约定了一个通信的规范通过一个握手的机制客户端和服务器之间能建立一个类似tcp的连接从而方便它们之间的通信在websocket出现之前web交互一般是基于http协议的短连接或者长连接websocket是一种全新的协议不属于http无状态协议协议名为 ws 优点减少资源消耗;实时推送不用等待客户端的请求;减少通信量;缺点少部分浏览器不支持不同浏览器支持的程度和方式都不同。 应用场景 智慧大屏消息提醒通知…
二、具体实现
2.1 编写pom
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId
/dependency2.2 websocket配置
Component
public class WebsocketConfig {Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}2.3 websocket服务端
ServerEndpoint(/wbsocket)
Component
Slf4j
public class Websocket {// 记录连接的客户端public static MapString, Session clients new ConcurrentHashMap();/*** userId关联sid解决同一用户id在多个web端连接的问题*/public static MapString, SetString cons new ConcurrentHashMap();private String sid null;// 一些记录发送消息状态private static int initFlag 0;private static int tempFlag 0;// 区分新旧消息的变量private static int sum 0;/*** 连接成功后调用的方法** param session 会话*/OnOpenpublic void onOpen(Session session) {this.sid UUID.randomUUID().toString();clients.put(this.sid, session);log.info(this.sid 连接开启);}/*** 连接关闭调用的方法*/OnClosepublic void onClose() {log.info(this.sid 连接断开);clients.remove(this.sid);}/*** 判断是否连接的方法** return 连接true, 未连接false*/public static boolean isServerClose() {if (CollectionUtils.isEmpty(Websocket.clients.values())) {log.info(已断开);return true;} else {log.info(已连接);return false;}}/*** 发送给所有用户** param noticeType 提醒类型*/public static boolean sendMessage(String noticeType, int count) {if (sum ! count) {WsResp noticeWsResp new WsResp();noticeWsResp.setNoticeType(noticeType);sendMessage(noticeWsResp);sum count;}//判断前端是否 回复了 收到消息 相等没收到不相等 收到if (initFlag tempFlag) {WsResp noticeWsResp new WsResp();noticeWsResp.setNoticeType(noticeType);sendMessage(noticeWsResp);} else {tempFlag initFlag;log.info(收到消息了别发同一个消息了);return true;}tempFlag initFlag;log.info(没收到消息继续发);return false;}/*** 发送给所有用户** param websocketResp websocket的返回*/public static void sendMessage(WsResp websocketResp) {String message JSONObject.toJSONString(websocketResp);for (Session session1 : Websocket.clients.values()) {try {session1.getBasicRemote().sendText(message);} catch (IOException e) {log.error(给所有用户的消息发送失败, msg: {}, message, e);}}}/*** 根据用户id发送给某一个用户**/public static void sendMessageByUserId(String userId, WsResp wsResp) {if (!StringUtils.isBlank(userId)) {String message JSONObject.toJSONString(wsResp);SetString clientSet cons.get(userId);if (clientSet ! null) {for (String sid : clientSet) {Session session clients.get(sid);if (session ! null) {try {session.getBasicRemote().sendText(message);} catch (IOException e) {log.error(用户消息发送失败, sid: {}, msg: {}, sid, message, e);}}}}}}/*** 收到客户端消息后调用的方法** param message 消息* param session 会话*/OnMessagepublic void onMessage(String message, Session session) {log.info(收到来自窗口 的信息: message);if (已接收到消息.equals(message)) {//收到消息改变flag的值log.info(前端已经收到消息开始改变 initFlag的值此时initFlag initFlag);initFlag initFlag 1;log.info(前端已经收到消息已经改变 initFlag的值此时initFlag initFlag);}}/*** 发生错误时的回调函数** param error 错误*/OnErrorpublic void onError(Throwable error) {log.info(错误);}
}2.4 service impl 编写
public interface RecycleCustomerService {void sendMsg(WsMsgVO msgVO);
}Slf4j
Service
public class RecycleCustomerServiceImpl implements RecycleCustomerService {private static final AtomicInteger count new AtomicInteger(0);Overridepublic void sendMsg(WsMsgVO msgVO) {// 测试websocket,实现新增客户往前端推送消息直到前端回复boolean flag false;do {// 休息300毫秒try { Thread.sleep(300); } catch (InterruptedException e) { log.error(休息时出错~~~~~~~, e);}// 往前端发送消息flag Websocket.sendMessage(实时数据: msgVO.toString(), count.get());if (flag) {log.info(停止往前端发送数据, 因为 resultFlag 为: {}, 说明前端接收到消息, flag);} else {log.info(往前端发送数据, 因为 resultFlag 为: {}, flag);}} while (!flag);log.info(停止往前端发送数据, 因为 delFlag 为: {}, flag);int count RecycleCustomerServiceImpl.count.incrementAndGet();log.info(当前count: {}, count);}
}2.5 index.html编写
!DOCTYPE html
html langen
headmeta charsetUTF-8titleSseEmitter/title
/head
body
div idmessage/div
/body
scriptlet limitConnect 0;init();function init() {// 开启 wbsocket 服务的ip地址 ws:// ip地址 访问路径let ws new WebSocket(ws://127.0.0.1:8888/wbsocket);// 获取连接状态console.log(ws连接状态 ws.readyState);// 监听是否连接成功ws.onopen function () {console.log(ws连接状态 ws.readyState);limitConnect 0;//连接成功则发送一个数据ws.send(我们建立连接啦);}// 接听服务器发回的信息并处理展示ws.onmessage function (data) {console.log(接收到来自服务器的消息);console.log(data);//接收到 消息后给后端发送的 确认收到消息后端接收到后 不再重复发消息ws.send(已接收到消息);//完成通信后关闭WebSocket连接// ws.close();}// 监听连接关闭事件ws.onclose function () {// 监听整个过程中websocket的状态console.log(ws连接状态 ws.readyState);reconnect();}// 监听并处理error事件ws.onerror function (error) {console.log(error);}}function reconnect() {limitConnect;console.log(重连第 limitConnect 次);setTimeout(function () {init();}, 2000);}
/script
/html三、运行并测试 调用: http://127.0.0.1:8888/ws/test 可以看到控制台打印 websocket测试成功
代码地址: websocket-demo