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测试通信结果,前端可以打印信息
  • 相关阅读:
    牛客前缀和题、枚举---[HNOI2003]激光炸弹
    牛客贪心题---拼数
    牛客枚举题---明明的随机数
    牛客模拟、差分题---校门外的树
    牛客贪心题---纪念品分组
    03_7_继承和权限控制
    03_6_package和import语句
    03_5_static关键字
    01_8_sql主键生成方式
    01_7_模糊查询实体对象
  • 原文地址:https://www.cnblogs.com/zuiyue_jing/p/15017243.html
Copyright © 2011-2022 走看看