zoukankan      html  css  js  c++  java
  • Websocket使用——Spring Boot配置websocket

    步骤

    • 引入依赖
    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    • 创建配置
    @Configuration
    public class WebsocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
    }
    • 创建service
    @Component
    @ServerEndpoint("/websocket/{userName}")
    public class WebSocketServiceImpl {
        private Session session;
    
        private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>();
        private static Map<String,Session> sessionPool = new HashMap<String,Session>();
    
        @OnOpen
        public void onOpen(Session session, @PathParam(value="userName")String userName) {
            this.session = session;
            webSockets.add(this);
            sessionPool.put(userName, session);
            System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
        }
    
        @OnClose
        public void onClose() {
            webSockets.remove(this);
            System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
        }
    
        @OnMessage
        public void onMessage(String message) {
            System.out.println("【websocket消息】收到客户端消息:"+message);
        }
    
        // 此为广播消息
        public void sendAllMessage(String message) {
            for(WebSocketServiceImpl webSocket : webSockets) {
                System.out.println("【websocket消息】广播消息:"+message);
                try {
                    webSocket.session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        // 此为单点消息
        public void sendOneMessage(String userName, String message) {
            System.out.println("【websocket消息】单点消息:"+message);
            Session session = sessionPool.get(userName);
            if (session != null) {
                try {
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
      • 注意此处@ServerEndpoint注解的值要和前端通信的接口地址保持一致,否则不能连接通信。
    • Websocket Server 已经搭建完成,客户端已经可以和服务端通信了。服务端 向客户端推送消息 通过 session.getBasicRemote().sendText(message)

    测试

    • 代码如下
    @RequestMapping("/websocket")
    @RestController
    public class WebSocketController {
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        @Autowired
        private WebSocketServiceImpl webSocketService;
    
        @ResponseBody
        @GetMapping("/sendAllWebSocket")
        public String test() {
            String text="你们好!这是websocket群体发送!";
            webSocketService.sendAllMessage(text);
            return text;
        }
    
        @GetMapping("/sendOneWebSocket/{userName}")
        public String sendOneWebSocket(@PathVariable("userName") String userName) {
            String text=userName+" 你好! 这是websocket单人发送!";
            webSocketService.sendOneMessage(userName,text);
            return text;
        }
    }
      • 通过url测试通信结果,前端可以打印信息
  • 相关阅读:
    Mybatis中Log4j日志的使用
    Mybatis结果集ResultMap映射
    Mybatis中的基本对象的生命周期和作用域
    IAR瑞萨单片机开发加入printf调试函数
    【转】C语言mem.h中的函数介绍
    【转】c语言位域操作—_结构体内冒号:的使用
    串口数据传输当中的共用体和结构体转换
    【转】printf格式串中的%f的输出格式和内容
    【转】缓冲区设计--环形队列(C++)
    【转】环形队列理论(C语言)
  • 原文地址:https://www.cnblogs.com/zuiyue_jing/p/15017243.html
Copyright © 2011-2022 走看看