WebSocket Transport

本部分解释了如何配置基础 WebSocket 服务器传输。

对于 Jakarta WebSocket 服务器,将`ServletServerContainerFactoryBean`添加到你的配置。例如,请参阅 WebSocket 部分下的Configuring the Server

对于 Jetty WebSocket 服务器,请按照以下方式自定义 JettyRequestUpgradeStrategy

  • Java

  • Kotlin

@Configuration
@EnableWebSocketMessageBroker
public class JettyWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/portfolio").setHandshakeHandler(handshakeHandler());
	}

	@Bean
	public DefaultHandshakeHandler handshakeHandler() {
		JettyRequestUpgradeStrategy strategy = new JettyRequestUpgradeStrategy();
		strategy.addWebSocketConfigurer(configurable -> {
			configurable.setInputBufferSize(4 * 8192);
			configurable.setIdleTimeout(Duration.ofSeconds(600));
		});
		return new DefaultHandshakeHandler(strategy);
	}
}
@Configuration
@EnableWebSocketMessageBroker
class JettyWebSocketConfiguration : WebSocketMessageBrokerConfigurer {

	override fun registerStompEndpoints(registry: StompEndpointRegistry) {
		registry.addEndpoint("/portfolio").setHandshakeHandler(handshakeHandler())
	}

	@Bean
	fun handshakeHandler(): DefaultHandshakeHandler {
		val strategy = JettyRequestUpgradeStrategy()
		strategy.addWebSocketConfigurer {
			it.inputBufferSize = 4 * 8192
			it.idleTimeout = Duration.ofSeconds(600)
		}
		return DefaultHandshakeHandler(strategy)
	}
}

除了 WebSocket 服务器属性之外,还有以下要自定义的 STOMP WebSocket 传输属性:

  • Java

  • Kotlin

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
		registry.setMessageSizeLimit(4 * 8192);
		registry.setTimeToFirstMessage(30000);
	}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfiguration : WebSocketMessageBrokerConfigurer {

	override fun configureWebSocketTransport(registry: WebSocketTransportRegistration) {
		registry.setMessageSizeLimit(4 * 8192)
		registry.setTimeToFirstMessage(30000)
	}
}