springboot集成websocket需要三步:
- 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
添加配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}
添加Websocket监听类
@ServerEndpoint("/webSocket")
@Component
public class WebSocketServer {
private static AtomicInteger onlineNum = new AtomicInteger();
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
//发送消息
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
System.out.println("发送数据:" + message);
session.getBasicRemote().sendText(message);
}
}
}
//建立连接成功调用
@OnOpen
public void onOpen(Session session){
addOnlineCount();
System.out.println("加入webSocket!当前人数为" + onlineNum);
// 广播上线消息
}
//关闭连接时调用
@OnClose
public void onClose(){
subOnlineCount();
System.out.println("断开webSocket连接!当前人数为" + onlineNum);
}
//收到客户端信息
@OnMessage
public void onMessage(String message) throws IOException{
System.out.println("server get" + message);
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("发生错误");
throwable.printStackTrace();
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
public static AtomicInteger getOnlineNumber() {
return onlineNum;
}
public static ConcurrentHashMap<String, Session> getSessionPools() {
return sessionPools;
}
}
用websocket在线测试验证:
websocket在线测试
控制台接受消息:
当发送一个超长的文本内容时(超过8kb)出现了以下问题:
发现断开了连接!
接下来我们只需要配置两个参数即可解决:
改造原来的配置类:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements ServletContextInitializer {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(WebAppRootListener.class);
servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize","52428800");
servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize","52428800");
}
}
配置org.apache.tomcat.websocket.textBufferSize、org.apache.tomcat.websocket.binaryBufferSize 的值为50M,再进行尝试,success!