Spring 中使用 WebSocket 笔记
Posted _路上
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 中使用 WebSocket 笔记相关的知识,希望对你有一定的参考价值。
public class WebSocketHandler extends AbstractWebSocketHandler { ? @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { logger.info("Received message: " + message.getPayload()); TimeUnit.SECONDS.sleep(2); session.sendMessage(new TextMessage("Polo!")); } }
启用 WebSocket,并映射消息处理器
@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer{ ? // 要映射的 WebSocket 消息处理器(类) @Bean public WebSocketHandler webSocketHandler() { return new WebSocketHandler(); } // 映射消息处理器到对应的路径 @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler(), "/macro"); } ? }
之后即可在 javascript 端进行互相通信,demo 如下
var url = ‘ws://‘ + window.location.host + ‘/demo/macro‘; var sock = new WebSocket(url); sock.onopen = function() { console.log("Opening"); sayMarco(); } sock.onmessage = function(e) { console.log("Received messaage: " + e.data); setTimeout(function(){sayMarco()}, 2000); } sock.onclose = function() { console.log("Closing"); } function sayMarco() { console.log(‘Sending Marco!‘); sock.send(‘Marco!‘); }
以上是关于Spring 中使用 WebSocket 笔记的主要内容,如果未能解决你的问题,请参考以下文章