一.引入依赖
org.springframework.boot
spring-boot-starter-websocket
二.注入ServerEndpointExporter
编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,
这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.socket.server.standard.ServerEndpointExporter;/*** @Description: 编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint*/@Configurationpublic classWebSocketConfig {
@BeanpublicServerEndpointExporter serverEndpointExporter() {return newServerEndpointExporter();
}
}
三.websocket的具体实现类
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,
但在springboot中连容器都是spring管理的。
虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
所以可以用一个静态set保存起来。
importorg.springframework.stereotype.Component;import javax.websocket.*;importjavax.websocket.server.ServerEndpoint;importjava.util.concurrent.CopyOnWriteArraySet;/*** * @Description: websocket的具体实现类
* * 使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,
* * 但在springboot中连容器都是spring管理的。
* 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
* 所以可以用一个静态set保存起来。*/@ServerEndpoint(value= "/websocket")
@Componentpublic classMyWebSocket {//用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();//与某个客户端的连接会话,需要通过它来给客户端发送数据
privateSession session;/*** 连接建立成功调用的方法*/@OnOpenpublic voidonOpen(Session session) {this.session =

本文介绍了如何在SpringBoot应用中集成WebSocket,创建在线聊天室。首先引入相关依赖,然后配置WebSocketConfig类并注入ServerEndpointExporter。接着,创建WebSocket的实现类MyWebSocket,使用@ServerEndpoint和@Component注解,并使用静态集合保存连接。通过@OnOpen、@OnClose、@OnMessage和@OnError处理连接、关闭、接收消息和错误。在前端,使用HTML、JavaScript和CSS构建用户界面,实现连接、断开、发送和接收消息的功能。最后,调整代码以支持单聊功能,通过解析JSON消息,根据SocketMsg的type属性分别处理单聊和群聊消息。
最低0.47元/天 解锁文章
2925

被折叠的 条评论
为什么被折叠?



