問題說明:
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;
}
}