程序员的公众号:源1024,获取更多资料,无加密无套路!
近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等
获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上
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!文章来源:https://www.toymoban.com/news/detail-518132.html
文章来源地址https://www.toymoban.com/news/detail-518132.html
到了这里,关于websocket 发送的消息超过默认限制就会自动断开连接的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!