基于springboot实现最简单的websocket服务端实例
这里仅仅是为了模拟一个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]