编写 WebSocket 消息处理类,比较简单的方式就是直接继承AbstractWebSocketHandler
,并覆写其中的处理方法,下面为一个简单的 demo
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!‘); }
时间: 2024-11-09 06:14:00