spring websocket源码分析续Handler的使用
生活随笔
收集整理的這篇文章主要介紹了
spring websocket源码分析续Handler的使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. handler的定義
spring websocket支持的消息有以下幾種:
對(duì)消息的處理就使用了Handler模式,抽象handler類(lèi)AbstractWebSocketHandler.java
@Overridepublic void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {if (message instanceof TextMessage) {handleTextMessage(session, (TextMessage) message);}else if (message instanceof BinaryMessage) {handleBinaryMessage(session, (BinaryMessage) message);}else if (message instanceof PongMessage) {handlePongMessage(session, (PongMessage) message);}else {throw new IllegalStateException("Unexpected WebSocket message type: " + message);}}protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {}protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {}protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {}具體實(shí)現(xiàn)handler類(lèi)BinaryWebSocketHandler(為例,其它略)
public class BinaryWebSocketHandler extends AbstractWebSocketHandler {@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) {try {session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Text messages not supported"));}catch (IOException e) {// ignore }}}2.handler的使用
StandardWebSocketClient和服務(wù)端握手時(shí),調(diào)用
@Overrideprotected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler,HttpHeaders headers, final URI uri, List<String> protocols,List<WebSocketExtension> extensions, Map<String, Object> attributes) {int port = getPort(uri);InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port);InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port);final StandardWebSocketSession session = new StandardWebSocketSession(headers,attributes, localAddress, remoteAddress);final ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create();configBuilder.configurator(new StandardWebSocketClientConfigurator(headers));configBuilder.preferredSubprotocols(protocols);configBuilder.extensions(adaptExtensions(extensions));final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session);Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() {@Overridepublic WebSocketSession call() throws Exception {webSocketContainer.connectToServer(endpoint, configBuilder.build(), uri);return session;}};if (this.taskExecutor != null) {return this.taskExecutor.submitListenable(connectTask);}else {ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<WebSocketSession>(connectTask);task.run();return task;}}紅色部分調(diào)用一個(gè)適配器StandardWebSocketHandlerAdapter,它封裝了Handler的調(diào)用
@Overridepublic void onOpen(final javax.websocket.Session session, EndpointConfig config) {this.wsSession.initializeNativeSession(session);if (this.handler.supportsPartialMessages()) {session.addMessageHandler(new MessageHandler.Partial<String>() {@Overridepublic void onMessage(String message, boolean isLast) {handleTextMessage(session, message, isLast);}});session.addMessageHandler(new MessageHandler.Partial<ByteBuffer>() {@Overridepublic void onMessage(ByteBuffer message, boolean isLast) {handleBinaryMessage(session, message, isLast);}});}else {session.addMessageHandler(new MessageHandler.Whole<String>() {@Overridepublic void onMessage(String message) {handleTextMessage(session, message, true);}});session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {@Overridepublic void onMessage(ByteBuffer message) {handleBinaryMessage(session, message, true);}});}session.addMessageHandler(new MessageHandler.Whole<javax.websocket.PongMessage>() {@Overridepublic void onMessage(javax.websocket.PongMessage message) {handlePongMessage(session, message.getApplicationData());}});try {this.handler.afterConnectionEstablished(this.wsSession);}catch (Throwable t) {ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger);return;}}具體實(shí)現(xiàn)
private void handleTextMessage(javax.websocket.Session session, String payload, boolean isLast) {TextMessage textMessage = new TextMessage(payload, isLast);try {this.handler.handleMessage(this.wsSession, textMessage);}catch (Throwable t) {ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger); } } private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer payload, boolean isLast) { BinaryMessage binaryMessage = new BinaryMessage(payload, isLast); try { this.handler.handleMessage(this.wsSession, binaryMessage); } catch (Throwable t) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger); } } private void handlePongMessage(javax.websocket.Session session, ByteBuffer payload) { PongMessage pongMessage = new PongMessage(payload); try { this.handler.handleMessage(this.wsSession, pongMessage); } catch (Throwable t) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, t, logger); }?
轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/5672677.html
總結(jié)
以上是生活随笔為你收集整理的spring websocket源码分析续Handler的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java 线程池框架核心代码分析--转
- 下一篇: 微服务实战(二):使用API Gatew