zoukankan      html  css  js  c++  java
  • 基于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] 
  • 相关阅读:
    推荐阅读20100603
    [ASP.NET4之旅]Circular file references are not allowed
    满园尽是503,记曾经的一次IIS 7性能考验
    VS2010小Bug:找不到System.Web.Extensions.dll引用
    VS2010奇异Bug:三个中文符号在CSS文件中轻松让VS2010崩溃
    推荐阅读20100528
    Windows平台网站文件同步备份解决方案——cwRsyn
    推荐阅读20100803
    在IE8中使用建行企业网银的解决方法
    博客园已经用上NorthScale Memcached Server
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/13182558.html
Copyright © 2011-2022 走看看