websocket 发送的消息超过默认限制就会自动断开连接 |
您所在的位置:网站首页 › usb3传输一会就断开连接 › websocket 发送的消息超过默认限制就会自动断开连接 |
程序员的公众号:源1024,获取更多资料,无加密无套路!
近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等 获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上 springboot集成websocket需要三步: 添加依赖 org.springframework.boot spring-boot-starter-websocket 2.1.6.RELEASE添加配置类 @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 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 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! |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |