websocket通信1009错误,

问题说明:

springboot继承 WebSocketConfigurer实现websocket通信服务,服务器端报错,“The decoded text message was too big for the output buffer and the endpoint does not support partial messages”,浏览器端显示服务器上的该次会话已经关闭。1009错误,内容长度超限。

问题解决

在应用启动类中通过注解注入方式设置通信的文本和二进制消息的大小。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private MyHandler myHandler;

    /**
     * sockJs 低版本浏览器不支持webSocket时使用
     * url结构:http://host:port/{endpoint}/{server-id}/{session-id}/websocket
     * 也可以: ws://host:port/{endpoint}/websocket
     * <p>
     * 不使用sockJs 访问时 url: ws://host:port/{endpoint}
     * <p>
     * setClientLibraryUrl 兼容客户端sockJs版本
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
 
        registry.addHandler(myHandler, "/myHandler").setAllowedOrigins("*");
        registry.addHandler(myHandler, "/myHandler").setAllowedOrigins("*").withSockJS()
                .setTaskScheduler(sockJsScheduler()).setClientLibraryUrl("//cdn.jsdelivr.net/sockjs/1/sockjs.min.js");
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        // ws 传输数据的时候,数据过大有时候会接收不到,所以在此处设置bufferSize
        container.setMaxTextMessageBufferSize(512000);
        container.setMaxBinaryMessageBufferSize(512000);
        container.setMaxSessionIdleTimeout(15 * 60000L);
        return container;
    }

}

猜你喜欢

转载自www.cnblogs.com/Pan-xi-yi/p/12003190.html
今日推荐