Class SubProtocolWebSocketHandler
- All Implemented Interfaces:
Lifecycle,Phased,SmartLifecycle,MessageHandler,SubProtocolCapable,WebSocketHandler
WebSocketHandler that delegates incoming WebSocket
messages to a SubProtocolHandler along with a MessageChannel to which
the sub-protocol handler can send messages from WebSocket clients to the application.
Also an implementation of MessageHandler that finds the WebSocket session
associated with the Message and passes it, along with the message, to the
sub-protocol handler to send messages from the application back to the client.
- Since:
- 4.0
- Author:
- Rossen Stoyanchev, Juergen Hoeller, Andy Wilkinson, Artem Bilan
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceContract for access to session counters. -
Field Summary
Fields inherited from interface org.springframework.context.SmartLifecycle
DEFAULT_PHASE -
Constructor Summary
ConstructorsConstructorDescriptionSubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) Create a newSubProtocolWebSocketHandlerfor the given inbound and outbound channels. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddProtocolHandler(SubProtocolHandler handler) Register a sub-protocol handler.voidafterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) Invoked after the WebSocket connection has been closed by either side, or after a transport error has occurred.voidInvoked after WebSocket negotiation has succeeded and the WebSocket connection is opened and ready for use.protected WebSocketSessiondecorateSession(WebSocketSession session) Decorate the givenWebSocketSession, if desired.protected final SubProtocolHandlerfindProtocolHandler(WebSocketSession session) Find aSubProtocolHandlerfor the given session.Return the default sub-protocol handler to use.intgetPhase()Return the phase that this lifecycle object is supposed to run in.Return the sub-protocols keyed by protocol name.intReturn the buffer-size limit (number of bytes).intReturn the send-time limit (milliseconds).getStats()Return a structured object with various session counters.Return a String describing internal state and counters.Return all supported protocols.intReturn the maximum time allowed after the WebSocket connection is established and before the first sub-protocol message.voidhandleMessage(Message<?> message) Handle an outbound Spring Message to a WebSocket client.voidhandleMessage(WebSocketSession session, WebSocketMessage<?> message) Handle an inbound message from a WebSocket client.voidhandleTransportError(WebSocketSession session, Throwable exception) Handle an error from the underlying WebSocket message transport.final booleanCheck whether this component is currently running.voidsetDefaultProtocolHandler(SubProtocolHandler defaultProtocolHandler) Set theSubProtocolHandlerto use when the client did not request a sub-protocol.voidsetPhase(int phase) Set the phase that this handler should run in.voidsetProtocolHandlers(List<SubProtocolHandler> protocolHandlers) Configure one or more handlers to use depending on the sub-protocol requested by the client in the WebSocket handshake request.voidsetSendBufferSizeLimit(int sendBufferSizeLimit) Specify the buffer-size limit (number of bytes).voidsetSendTimeLimit(int sendTimeLimit) Specify the send-time limit (milliseconds).voidsetTimeToFirstMessage(int timeToFirstMessage) Set the maximum time allowed in milliseconds after the WebSocket connection is established and before the first sub-protocol message is received.final voidstart()Start this component.final voidstop()Stop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method.final voidIndicates that a Lifecycle component must stop if it is currently running.booleanWhether the WebSocketHandler handles partial messages.toString()Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.springframework.context.SmartLifecycle
isAutoStartup
-
Constructor Details
-
SubProtocolWebSocketHandler
public SubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) Create a newSubProtocolWebSocketHandlerfor the given inbound and outbound channels.- Parameters:
clientInboundChannel- the inboundMessageChannelclientOutboundChannel- the outboundMessageChannel
-
-
Method Details
-
setProtocolHandlers
Configure one or more handlers to use depending on the sub-protocol requested by the client in the WebSocket handshake request.- Parameters:
protocolHandlers- the sub-protocol handlers to use
-
getProtocolHandlers
-
addProtocolHandler
Register a sub-protocol handler. -
getProtocolHandlerMap
Return the sub-protocols keyed by protocol name. -
setDefaultProtocolHandler
Set theSubProtocolHandlerto use when the client did not request a sub-protocol.- Parameters:
defaultProtocolHandler- the default handler
-
getDefaultProtocolHandler
Return the default sub-protocol handler to use. -
getSubProtocols
Return all supported protocols.- Specified by:
getSubProtocolsin interfaceSubProtocolCapable
-
setSendTimeLimit
public void setSendTimeLimit(int sendTimeLimit) Specify the send-time limit (milliseconds).- See Also:
-
getSendTimeLimit
public int getSendTimeLimit()Return the send-time limit (milliseconds). -
setSendBufferSizeLimit
public void setSendBufferSizeLimit(int sendBufferSizeLimit) Specify the buffer-size limit (number of bytes).- See Also:
-
getSendBufferSizeLimit
public int getSendBufferSizeLimit()Return the buffer-size limit (number of bytes). -
setTimeToFirstMessage
public void setTimeToFirstMessage(int timeToFirstMessage) Set the maximum time allowed in milliseconds after the WebSocket connection is established and before the first sub-protocol message is received.This handler is for WebSocket connections that use a sub-protocol. Therefore, we expect the client to send at least one sub-protocol message in the beginning, or else we assume the connection isn't doing well, e.g. proxy issue, slow network, and can be closed.
By default this is set to
60,000(1 minute).- Parameters:
timeToFirstMessage- the maximum time allowed in milliseconds- Since:
- 5.1
- See Also:
-
checkSessions()
-
getTimeToFirstMessage
public int getTimeToFirstMessage()Return the maximum time allowed after the WebSocket connection is established and before the first sub-protocol message.- Since:
- 5.1
-
setPhase
public void setPhase(int phase) Set the phase that this handler should run in.By default, this is
SmartLifecycle.DEFAULT_PHASE.- Since:
- 6.1.4
-
getPhase
public int getPhase()Description copied from interface:SmartLifecycleReturn the phase that this lifecycle object is supposed to run in.The default implementation returns
SmartLifecycle.DEFAULT_PHASEin order to letstop()callbacks execute before regularLifecycleimplementations.- Specified by:
getPhasein interfacePhased- Specified by:
getPhasein interfaceSmartLifecycle- See Also:
-
getStatsInfo
Return a String describing internal state and counters. EffectivelytoString()ongetStats(). -
getStats
Return a structured object with various session counters.- Since:
- 5.2
-
start
public final void start()Description copied from interface:LifecycleStart this component.Should not throw an exception if the component is already running.
In the case of a container, this will propagate the start signal to all components that apply.
-
stop
public final void stop()Description copied from interface:LifecycleStop this component, typically in a synchronous fashion, such that the component is fully stopped upon return of this method. Consider implementingSmartLifecycleand itsstop(Runnable)variant when asynchronous stop behavior is necessary.Note that this stop notification is not guaranteed to come before destruction: On regular shutdown,
Lifecyclebeans will first receive a stop notification before the general destruction callbacks are being propagated; however, on hot refresh during a context's lifetime or on aborted refresh attempts, a given bean's destroy method will be called without any consideration of stop signals upfront.Should not throw an exception if the component is not running (not started yet).
In the case of a container, this will propagate the stop signal to all components that apply.
-
stop
Description copied from interface:SmartLifecycleIndicates that a Lifecycle component must stop if it is currently running.The provided callback is used by the
LifecycleProcessorto support an ordered, and potentially concurrent, shutdown of all components having a common shutdown order value. The callback must be executed after theSmartLifecyclecomponent does indeed stop.The
LifecycleProcessorwill call only this variant of thestopmethod; i.e.Lifecycle.stop()will not be called forSmartLifecycleimplementations unless explicitly delegated to within the implementation of this method.The default implementation delegates to
Lifecycle.stop()and immediately triggers the given callback in the calling thread. Note that there is no synchronization between the two, so custom implementations may at least want to put the same steps within their common lifecycle monitor (if any).- Specified by:
stopin interfaceSmartLifecycle- See Also:
-
isRunning
public final boolean isRunning()Description copied from interface:LifecycleCheck whether this component is currently running.In the case of a container, this will return
trueonly if all components that apply are currently running. -
afterConnectionEstablished
Description copied from interface:WebSocketHandlerInvoked after WebSocket negotiation has succeeded and the WebSocket connection is opened and ready for use.- Specified by:
afterConnectionEstablishedin interfaceWebSocketHandler- Throws:
Exception- this method can handle or propagate exceptions; see class-level Javadoc for details.
-
handleMessage
Handle an inbound message from a WebSocket client.- Specified by:
handleMessagein interfaceWebSocketHandler- Throws:
Exception- this method can handle or propagate exceptions; see class-level Javadoc for details.
-
handleMessage
Handle an outbound Spring Message to a WebSocket client.- Specified by:
handleMessagein interfaceMessageHandler- Parameters:
message- the message to be handled- Throws:
MessagingException- if the handler failed to process the message
-
handleTransportError
Description copied from interface:WebSocketHandlerHandle an error from the underlying WebSocket message transport.- Specified by:
handleTransportErrorin interfaceWebSocketHandler- Throws:
Exception- this method can handle or propagate exceptions; see class-level Javadoc for details.
-
afterConnectionClosed
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception Description copied from interface:WebSocketHandlerInvoked after the WebSocket connection has been closed by either side, or after a transport error has occurred. Although the session may technically still be open, depending on the underlying implementation, sending messages at this point is discouraged and most likely will not succeed.- Specified by:
afterConnectionClosedin interfaceWebSocketHandler- Throws:
Exception- this method can handle or propagate exceptions; see class-level Javadoc for details.
-
supportsPartialMessages
public boolean supportsPartialMessages()Description copied from interface:WebSocketHandlerWhether the WebSocketHandler handles partial messages. If this flag is set totrueand the underlying WebSocket server supports partial messages, then a large WebSocket message, or one of an unknown size may be split and maybe received over multiple calls toWebSocketHandler.handleMessage(WebSocketSession, WebSocketMessage). The flagWebSocketMessage.isLast()indicates if the message is partial and whether it is the last part.- Specified by:
supportsPartialMessagesin interfaceWebSocketHandler
-
decorateSession
Decorate the givenWebSocketSession, if desired.The default implementation builds a
ConcurrentWebSocketSessionDecoratorwith the configuredsend-time limitandbuffer-size limit.- Parameters:
session- the originalWebSocketSession- Returns:
- the decorated
WebSocketSession, or potentially the given session as-is - Since:
- 4.3.13
-
findProtocolHandler
Find aSubProtocolHandlerfor the given session.- Parameters:
session- theWebSocketSessionto find a handler for
-
toString
-