Springboot中使用websocket发送信息给指定用户和群发

您所在的位置:网站首页 下发流程的通知怎么发给客户 Springboot中使用websocket发送信息给指定用户和群发

Springboot中使用websocket发送信息给指定用户和群发

2024-07-16 20:05:52| 来源: 网络整理| 查看: 265

       websocket是一种长连接协议,相较于传统的http短连接,websocket不仅可以由客户端向服务器发送消息,可以主动向客户端发起信息,经常用于及时聊天,游戏和服务器向客户端推送信息。

主要优点:

1. 节约带宽。 不停地轮询服务端数据这种方式,使用的是http协议,head信息很大,有效数据占比低, 而使用WebSocket方式,头信息很小,有效数据占比高。2. 无浪费。 轮询方式有可能轮询10次,才碰到服务端数据更新,那么前9次都白轮询了,因为没有拿到变化的数据。 而WebSocket是由服务器主动回发,来的都是新数据。

3. 实时性,考虑到服务器压力,使用轮询方式不可能很短的时间间隔,否则服务器压力太多,所以轮询时间间隔都比较长,好几秒,设置十几秒。 而WebSocket是由服务器主动推送过来,实时性是最高。

接下来我们看看怎么在springboot中使用websocket和html页面交互:

首先新建springboot项目,导入需要的websocket和springboot依赖,pom.xml配置如下:

4.0.0 com.lk websocketdemo 0.0.1-SNAPSHOT jar websocketdemo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin

application.properties中配置tomcat端口,我配置的是80:

server.port=80 然后就可以开始配置websocket了,首先创建WebSocket配置文件:WebSocketConfig.class @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }

再创建WebSocket服务器类:WebSocketServer.class,具体代码说明注释都写得很清楚了:

@Component //访问服务端的url地址 @ServerEndpoint(value = "/websocket/{id}") public class WebSocketServer { private static int onlineCount = 0; private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; private static Logger log = LogManager.getLogger(WebSocketServer.class); private String id = ""; /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(@PathParam(value = "id") String id, Session session) { this.session = session; this.id = id;//接收到发送消息的人员编号 webSocketSet.put(id, this); //加入set中 addOnlineCount(); //在线数加1 log.info("用户"+id+"加入!当前在线人数为" + getOnlineCount()); try { sendMessage("连接成功"); } catch (IOException e) { log.error("websocket IO异常"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:" + message); //可以自己约定字符串内容,比如 内容|0 表示信息群发,内容|X 表示信息发给id为X的用户 String sendMessage = message.split("[|]")[0]; String sendUserId = message.split("[|]")[1]; try { if(sendUserId.equals("0")) sendtoAll(sendMessage); else sendtoUser(sendMessage,sendUserId); } catch (IOException e) { e.printStackTrace(); } } /** * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 发送信息给指定ID用户,如果用户不在线则返回不在线信息给自己 * @param message * @param sendUserId * @throws IOException */ public void sendtoUser(String message,String sendUserId) throws IOException { if (webSocketSet.get(sendUserId) != null) { if(!id.equals(sendUserId)) webSocketSet.get(sendUserId).sendMessage( "用户" + id + "发来消息:" + " " + message); else webSocketSet.get(sendUserId).sendMessage(message); } else { //如果用户不在线则返回不在线信息给自己 sendtoUser("当前用户不在线",id); } } /** * 发送信息给所有人 * @param message * @throws IOException */ public void sendtoAll(String message) throws IOException { for (String key : webSocketSet.keySet()) { try { webSocketSet.get(key).sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }

这时我们的webSocket后端已经创建好了,接下来写两个前端代码:

WebSocket Welcome Send Close var websocket = null; //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:80/websocket/2"); } else{ alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ 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 += innerHTML + ''; } //关闭连接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); } WebSocket Welcome Send Close var websocket = null; //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:80/websocket/1"); } else{ alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ 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 += innerHTML + ''; } //关闭连接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); }

两个前端代码都是一样的,不同的地方在于一个访问是new WebSocket("ws://localhost:80/websocket/1");一个是new WebSocket("ws://localhost:80/websocket/2");即访问id传参不同,这时启动springboot后台服务,再打开两个前端html文件:

根据之前在代码中定义的输入格式:“信息内容|接受者Id|”进行输入,当输入id为0时表示群发:

项目源码:https://github.com/wsliukang/websocketdemo



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭