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!'); }