這里僅僅是為了模擬一個websocket服務端用於測試客戶端的斷連重連,重點是websocket的連接,所以內容就比較隨意了,僅僅返回一個累加的整數。
1、引入spring boot的websocket包(版本號隨spring boot自動引入,實際上這里是5.2.5):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2、最簡化的配置類,一個端點,一個啟動bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * WebSocketMessageBrokerConfigurer 用來處理STOMP協議 */ @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 添加一個服務端點,來接收客戶端的連接 * @param registry */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ist").setAllowedOrigins("*"); } /** * 開啟WebSocket支持 * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3、一個簡單的websocket服務端:
/** * websocket服務端 */ import com.alibaba.fastjson.JSON; import org.springframework.web.bind.annotation.RestController; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @ServerEndpoint("/ist") @RestController public class RtasrWS { private static final AtomicInteger segId = new AtomicInteger(1); @OnOpen public void onOpen(Session session) { System.out.println("I'm open."); // 獲取請求url String url = session.getRequestURI().toString(); System.out.println("request url: " + url); // 獲取參數 if (session.getRequestParameterMap().get("appId") != null) { System.out.println("appId: " + session.getRequestParameterMap().get("appId").get(0)); } } private Object getResult() { Map<String, Object> result = new HashMap<>(); result.put("seg_id", segId.getAndIncrement()); return result; } @OnClose public void onClose() { System.out.println("I'm close."); } @OnMessage public void onMessage(String message, Session session) { System.out.println("I'm String onMessage."); sendMessage(session, JSON.toJSONString(getResult())); } @OnMessage public void onMessage(byte[] message, Session session) { System.out.println("I'm byte onMessage."); sendMessage(session, JSON.toJSONString(getResult())); } @OnError public void onError(Session session, Throwable error) { System.out.println("I'm error: " + error.getMessage()); } private static void sendMessage(Session session, String message) { if (session == null) return; System.out.println("send msg : " + message); if (session.isOpen() && message.length() != 0) { try { session.getBasicRemote().sendText(message); } catch (Exception e) { System.out.println("send message error : " + e.getMessage()); e.printStackTrace(); } } } }
就這樣了,跑下spring boot,測試一下吧,我們用網頁版的websocket客戶端來測試,百度一下,最前面的是http://www.websocket-test.com,就它了:
日志:
2020-06-23 15:48:00 [http-nio-8089-exec-1] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 0 ms I'm open. request url: ws://127.0.0.1:8089/ist I'm String onMessage. send msg : {"seg_id":1} I'm String onMessage. send msg : {"seg_id":2} I'm String onMessage. send msg : {"seg_id":3} I'm String onMessage. send msg : {"seg_id":4} 2020-06-23 15:48:41 [MessageBroker-1] INFO o.s.web.socket.config.WebSocketMessageBrokerStats - WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]