SpringBoot使用Websocket
webSocket是HTML5的一种新协议,它实现了服务端与客户端的全双工通信,建立在传输层,tcp协议之上,即浏览器与服务端需要先建立tcp协议,再发送webSocket连接建立请求。webSocket的连接:客户端发送请求信息,服务端接受到请求并返回相应的信息。连接建立。客户端发送http请求时,通过 Upgrade:webSocket Connection:Upgrade 告知服务器需要建立的是webSocket连接,并且还会传递webSocket版本号,协议的字版本号,原始地址,主机地址, webSocket相互通信的Header很小,大概只有2Bytes
SpringBoot结合WebSocket实现群发消息
一. 消息群发
1. 导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
2. 新建WebSocket配置类
@Configuration
public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
3. 新建WebSocket服务端
@ServerEndpoint("/test")
@Component
@Slf4j
public class MyWebsocketServer {/*** 存放所有在线的客户端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();@OnOpenpublic void onOpen(Session session) {log.info("有新的客户端连接了: {}", session.getId());//将新用户存入在线的组clients.put(session.getId(), session);}/*** 客户端关闭* @param session session*/@OnClosepublic void onClose(Session session) {log.info("有用户断开了, id为:{}", session.getId());//将掉线的用户移除在线的组里clients.remove(session.getId());}/*** 发生错误* @param throwable e*/@OnErrorpublic void onError(Throwable throwable) {throwable.printStackTrace();}/*** 收到客户端发来消息* @param message 消息对象*/@OnMessagepublic void onMessage(String message) {log.info("服务端收到客户端发来的消息: {}", message);this.sendAll(message);}/*** 群发消息* @param message 消息内容*/private void sendAll(String message) {for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {sessionEntry.getValue().getAsyncRemote().sendText(message);}}
}
4. 启动后,客户端连接websocket
5. 客户端发送消息得到的响应和服务端的响应
- 客户端
- 服务端
SpringBoot结合WebSocket实现一对一发送消息
导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId>
</dependency>
新建Websocket配置类
@Configuration
public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
新建消息对象
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message {private String userId;private String message;
}
新建websocket服务
@ServerEndpoint("/test-one")
@Component
@Slf4j
public class MyOneToOneServer {/*** 用于存放所有在线客户端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();private Gson gson = new Gson();@OnOpenpublic void onOpen(Session session) {log.info("有新的客户端上线: {}", session.getId());clients.put(session.getId(), session);}@OnClosepublic void onClose(Session session) {String sessionId = session.getId();log.info("有客户端离线: {}", sessionId);clients.remove(sessionId);}@OnErrorpublic void onError(Session session, Throwable throwable) {throwable.printStackTrace();if (clients.get(session.getId()) != null) {clients.remove(session.getId());}}@OnMessagepublic void onMessage(String message) {log.info("收到客户端发来的消息: {}", message);this.sendTo(gson.fromJson(message, Message.class));}/*** 发送消息** @param message 消息对象*/private void sendTo(Message message) {Session s = clients.get(message.getUserId());if (s != null) {try {s.getBasicRemote().sendText(message.getMessage());} catch (IOException e) {e.printStackTrace();}}}
}
测试
- 上线两个客户端
- 使用其中一个客户端发送消息给另外一个,只需要带上另外一个客户端的id
- 接收方客户端
SpringBoot使用Websocket相关推荐
- SpringBoot 集成 WebSocket,实现后台向前端推送信息
作者 | 大树先生 来源 | https://blog.csdn.net/MacWx/article/details/111319558 前言 在一次项目开发中,使用到了Netty网络应用框架,以及M ...
- SpringBoot集成WebSocket,实现后台向前端推送信息
作者 | 大树先生 来源 | https://blog.csdn.net/MacWx/article/details/111319558 前言 在一次项目开发中,使用到了Netty网络应用框架,以及M ...
- Springboot集成websocket实例
一.简介 WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数 ...
- Springboot整合Websocket遇到的坑_websocket session不支持序列化,无法存储至redis_Websocket相关问题总结(Session共享,用户多端登录等)
Springboot整合Websocket遇到的坑 一.使用Springboot内嵌的tomcat启动websocket 1.添加ServerEndpointExporter配置bean @Confi ...
- springboot中websocket服务怎么调用其他类的方法
前言: 之前有写过一个springboot整合websocket的博客(SpringBoot 集成websocket_清泉影月的博客-CSDN博客),最开始的使用场景就是用websocket发消息给其 ...
- 最简单的springboot整合websocket方式
简介 WebSocket是一种与HTTP不同的协议.两者都位于OSI模型的应用层,并且都依赖于传输层的TCP协议. 虽然它们不同,但是RFC 6455中规定:it is designed to wor ...
- SpringBoot基于websocket的网页聊天
一.入门简介 正常聊天程序需要使用消息组件ActiveMQ或者Kafka等,这里是一个Websocket入门程序. 有人有疑问这个技术有什么作用,为什么要有它? 其实我们虽然有http协议,但是它有一 ...
- Springboot 整合Websocket+Stomp协议+RabbitMQ做消息代理 实例教程
前言 如果你还没有了解过websocket,关于整合websocket的简单入门使用,可以先看看我这篇: <SpringBoot 整合WebSocket 简单实战案例> https://b ...
- 在线聊天室的消息单聊的实现——springboot整合WebSocket(二)
一.声明 项目的搭建请大家移步到:在线聊天室的消息群聊的实现--springboot整合WebSocket(一) 单聊的实现是在群聊项目上进行延申改造的. 二.引入依赖 <dependency& ...
最新文章
- POJ 3628 Bookshelf 2
- Java常见问题汇总
- software on macbook pro
- Python 面向对象与 C++、Java 的异同
- oracle or使用速度快马_使用mysqld_exporter监控MySQL并展示数据
- 高电压技术思维导图_钢铁技术:钢铁行业板坯连铸结晶器振动常见故障思维导图...
- 《深入实践Spring Boot》下载
- 项目案例:qq数据库管理_2小时元项目:项目管理您的数据科学学习
- Android 多级树形菜单
- 利用python实现冒泡排序_利用python实现冒泡排序
- java 抽象类 静态变量_Java基础之 接口、抽象类、构造方法、setXxx,getXxx、静态变量和成员变量、代码块、this和super的区别、final关键字、重写与重载...
- oracle pivot 去除引号,使用pivot显示列式统计结果实例
- 常用数据库的字段类型及大小
- eclipse哪个版本最稳定_新版鹿鼎记开播啦,你最喜欢哪个版本?最还原原著的原来是他...
- 全球及中国DIN 2353压缩配件行业研究及十四五规划分析报告
- EMW3080+STC15轻松实现设备上云4(阿里云物联网平台、智能生活开放平台)
- MySQL 中的 “My” 是什么意思?
- ORACLE学习详解
- Linux 文件系统(2)sda sdb 和 SATA IDE SCSI
- CSS3之其他常用属性