关键词:
参考技术A 近期,公司需要新增即时聊天的业务,于是用websocket 整合到Springboot完成业务的实现。一、我们来简单的介绍下websocket的交互原理:
1.客户端先服务端发起websocket请求;
2.服务端接收到请求之后,把请求响应返回给客户端;
3.客户端与服务端只需要一次握手即可完成交互通道;
二、webscoket支持的协议:基于TCP协议下,http协议和https协议;
http协议 springboot不需要做任何的配置
https协议则需要配置nignx代理,注意证书有效的问题 ---在这不做详细说明
三、开始我们的实现java后端的实现
1.添加依赖
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>$spring.version</version>
</dependency>
<!-- WebSocket -->
2.配置config
@ConditionalOnWebApplication
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer
@Bean
public ServerEndpointExporter serverEndpointExporter()
return new ServerEndpointExporter();
@Bean
public CustomSpringConfigurator customSpringConfigurator()
return new CustomSpringConfigurator();
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry)
registry.addEndpoint("/websocket").setAllowedOrigins("*")
.addInterceptors(new HttpSessionHandshakeInterceptor()).withSockJS();
public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware
private static volatile BeanFactory context;
@Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException
return context.getBean(clazz);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
CustomSpringConfigurator.context = applicationContext;
@Override
public void modifyHandshake(ServerEndpointConfig sec,
HandshakeRequest request, HandshakeResponse response)
super.modifyHandshake(sec,request,response);
HttpSession httpSession=(HttpSession) request.getHttpSession();
if(httpSession!=null)
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
@SpringBootApplication
@EnableCaching
@ComponentScan("com")
@EnableWebSocket
public class Application extends SpringBootServletInitializer
static final Logger logger = LoggerFactory.getLogger(Application.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(Application.class);
需要注意的是: @EnableWebSocket 一定要加在启动类上,不然springboot无法对其扫描进行管理;
@SeverEndpoint --将目标类定义成一个websocket服务端,注解对应的值将用于监听用户连接的终端访问地址,客户端可以通过URL来连接到websocket服务端。
四、设计思路:用map<房间id, 用户set>来保存房间对应的用户连接列表,当有用户进入一个房间的时候,就会先检测房间是否存在,如果不存在那就新建一个空的用户set,再加入本身到这个set中,确保不同房间号里的用户session不串通!
/**
* Create by wushuyu
* on 2020/4/30 13:24
*
*/
@ServerEndpoint(value = "/websocket/roomName", configurator = CustomSpringConfigurator.class)
@Component
public class WebSocketRoom
//连接超时--一天
private static final long MAX_TIME_OUT = 24*60*60*1000;
// key为房间号,value为该房间号的用户session
private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap<>();
//将用户的信息存储在一个map集合里
private static final Map<String, Object> users = new ConcurrentHashMap<>();
/**
*roomName 使用通用跳转,实现动态获取房间号和用户信息 格式:roomId|xx|xx
*/
@OnOpen
public void connect(@PathParam("roomName") String roomName, Session session)
String roomId = roomName.split("[|]")[0];
String nickname = roomName.split("[|]")[1];
String loginId = roomName.split("[|]")[2];
//设置连接超时时间
session.setMaxIdleTimeout(MAX_TIME_OUT);
try
//可实现业务逻辑
// 将session按照房间名来存储,将各个房间的用户隔离
if (!rooms.containsKey(roomId))
// 创建房间不存在时,创建房间
Set<Session> room = new HashSet<>();
// 添加用户
room.add(session);
rooms.put(roomId, room);
else // 房间已存在,直接添加用户到相应的房间
if (rooms.values().contains(session)) //如果房间里有此session直接不做操作
else //不存在则添加
rooms.get(roomId).add(session);
JSONObject jsonObject = new JSONObject();
-----
//根据自身业务情况实现业务
-----
users.put(session.getId(), jsonObject);
//向在线的人发送当前在线的人的列表 -------------可有可无,看业务需求
List<ChatMessage> userList = new LinkedList<>();
rooms.get(roomId)
.stream()
.map(Session::getId)
.forEach(s ->
ChatMessage chatMessage = new ChatMessage();
chatMessage.setDate(new Date());
chatMessage.setStatus(1);
chatMessage.setChatContent(users.get(s));
chatMessage.setMessage("");
userList.add(chatMessage);
);
// session.getBasicRemote().sendText(JSON.toJSONString(userList));
//向房间的所有人群发谁上线了
ChatMessage chatMessage = new ChatMessage(); ----将聊天信息封装起来。
chatMessage.setDate(new Date());
chatMessage.setStatus(1);
chatMessage.setChatContent(users.get(session.getId()));
chatMessage.setMessage("");
broadcast(roomId, JSON.toJSONString(chatMessage));
broadcast(roomId, JSON.toJSONString(userList));
catch (Exception e)
e.printStackTrace();
@OnClose
public void disConnect(@PathParam("roomName") String roomName, Session session)
String roomId = roomName.split("[|]")[0];
String loginId = roomName.split("[|]")[2];
try
rooms.get(roomId).remove(session);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setDate(new Date());
chatMessage.setUserName(user.getRealname());
chatMessage.setStatus(0);
chatMessage.setChatContent(users.get(session.getId()));
chatMessage.setMessage("");
users.remove(session.getId());
//向在线的人发送当前在线的人的列表 ----可有可无,根据业务要求
List<ChatMessage> userList = new LinkedList<>();
rooms.get(roomId)
.stream()
.map(Session::getId)
.forEach(s ->
ChatMessage chatMessage1 = new ChatMessage();
chatMessage1.setDate(new Date());
chatMessage1.setUserName(user.getRealname());
chatMessage1.setStatus(1);
chatMessage1.setChatContent(users.get(s));
chatMessage1.setMessage("");
userList.add(chatMessage1);
);
broadcast(roomId, JSON.toJSONString(chatMessage));
broadcast(roomId, JSON.toJSONString(userList));
catch (Exception e)
e.printStackTrace();
@OnMessage
public void receiveMsg( String msg, Session session)
try
ChatMessage chatMessage = new ChatMessage();
chatMessage.setUserName(user.getRealname());
chatMessage.setStatus(2);
chatMessage.setChatContent(users.get(session.getId()));
chatMessage.setMessage(msg);
// 按房间群发消息
broadcast(roomId, JSON.toJSONString(chatMessage));
catch (IOException e)
e.printStackTrace();
// 按照房间名进行群发消息
private void broadcast(String roomId, String msg)
rooms.get(roomId).forEach(s ->
try
s.getBasicRemote().sendText(msg); -----此还有一个getAsyncRemote()
catch (IOException e)
e.printStackTrace();
);
@OnError
public void onError(Throwable error)
error.printStackTrace();
友情提示:此session是websocket里的session,并非httpsession;
springboot2系列教程(十六)|整合websocket实现广播
前言如题,今天介绍的是SpringBoot整合WebSocket实现广播消息。什么是WebSocket?WebSocket为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服务器发送信息,反之也成立。WebSocket是通过一个socket来实现双工异步通信能力... 查看详情
javaspringboot整合websocket
【Java】SpringBoot整合WebSocketWebSocket简介WebSocket是一种协议,用于实现客户端和服务器之间的双向通信。它可以在单个TCP连接上提供全双工通信,避免了HTTP协议中的请求-响应模式,从而实现更高效的数据交换。WebSocket协议最初由HT... 查看详情
springboot整合websocket实现登录挤退现象
在项目期间遇到了同一个账号不能在不同的地方同时登录的情况,解决方法用到了websocket。关于websocket的原理网上有很多,我这里就不写了,推荐博客:https://www.cnblogs.com/myzhibie/p/4470065.html这里我主要记录一下websocket来实现的登... 查看详情
springboot整合websocket实现实时消息推送(代码片段)
0.开发环境JDK:1.8SpringBoot:2.1.1.RELEASE1.引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>< 查看详情
springboot2系列教程(十七)|整合websocket实现聊天室
...基础之上,为便于更好理解今天这一篇,推荐先阅读:「SpringBoot整合WebSocket实现广播消息」 查看详情
springboot整合websocket实现简单聊天室(代码片段)
项目结构:效果展示:实现步骤步骤一:添加依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency> 查看详情
springboot整合websocket实现实时消息推送(代码片段)
0.开发环境JDK:1.8SpringBoot:2.1.1.RELEASE1.引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>2.新建WebSocket配置类importorg.springframework.context.annotatio... 查看详情
springboot1.5.9整合websocket
一.WebSocket介绍 1.WebSocket是什么? WebSocket是协议,是HTML5开始提供的基于TCP(传输层)的一种新的网络协议, 它实现了浏览器与服务器全双工(full-duplex)通信,即允许服务器主动发送消息给客户端 WebSocket使得客... 查看详情
springboot整合websocket实现客户端与服务端通信(代码片段)
定义?WebSocket是通过单个TCP连接提供全双工(双向通信)通信信道的计算机通信协议。此WebSocketAPI可在用户的浏览器和服务器之间进行双向通信。用户可以向服务器发送消息并接收事件驱动的响应,而无需轮询服务器。它可以让... 查看详情
springboot整合websocket简单聊天室(代码片段)
springboot整合websocket(一)简单聊天室springboot整合websocket(一)简单聊天室springboot整合websocket(二)上传文件(引导篇)springboot整合websocket(三)上传文件(终篇& 查看详情
springboot-websocket实现及原理
本文章包括websocket面试相关问题以及springboot如何整合webSocket。参考文档https://blog.csdn.net/prayallforyou/article/details/53737901、https://www.cnblogs.com/bianzy/p/5822426.html webSocket是HTML5的一种新协议,它实现了服务端与客户端的全双工通信,... 查看详情
socketio介绍+springboot整合socketio完成实时通信(代码片段)
Socket.IO笔记即时通信是基于TCP长连接,建立连接之后,客户段/服务器可以无限次随时向对端发送数据,实现服务器数据发送的即时性HTTPHTTP是短链接,设计的目的是减少服务器的压力HTTP伪即时通讯轮询emmet长轮询l... 查看详情
springboot整合websocket,使用stomp协议,前后端整合实战(代码片段)
... 一篇极简风,最最最基础的方式整合websocket:《SpringBoot整合WebSocket简单实战案例》地址: https://blog.csdn.net/qq_35387940/article/details/ 查看详情
websocket教程springboot+maven整合(目录)
...、课程技术选型和浏览器兼容讲解简介:简单介绍什么是springboot、socketjs、stompjs,及解决使用浏览器兼容问题3、websocket广播、单播、组播介绍和使用场景说明简介:主要讲解websocket的一些概念,如广播,单播等,他们的基本区... 查看详情
springboot整合websocket遇到的坑
参考技术A如果客户端关闭了websocket,但服务端没有监听到关闭事件,即onClose方法没有调用,这是会发生的情况此时如果服务端向客户端推送消息,会出现异常告诉开发者:关闭了一个连接,并重新调用onClose方法 查看详情
springboot整合websocket后打包报错:javax.websocket.server.servercontainernotavailable
项目整合了websocket以后,打包多次都没有成功,原来是报错了,报错内容如下:ErrorstartingApplicationContext.Todisplaytheconditionsreportre-runyourapplicationwith‘debug‘enabled.org.springframework.boot.SpringApplication.reportFailure( 查看详情
springboot项目整合websocket源码分析
背景在一个Springboot项目中,写了一个WebSocket服务端代码。具体代码网上一大堆,这里不再展示。同时,我在Websocket服务端的类里面,定义了一个Boolean类型的成员变量。当客户端websocket传来的参数是666时,将该... 查看详情
重学springboot系列之服务器推送技术(代码片段)
重学Springboot系列之服务器推送技术主流服务器推送技术说明需求与背景服务端推送常用技术全双工通信:WebSocket服务端主动推送:SSE(ServerSendEvent)websocket与SSE比较服务端推送事件SSE模拟网络支付场景应用场景sse规范模拟实现服务端... 查看详情