zoukankan      html  css  js  c++  java
  • SpringBoot集成WebSocket让后台主动给前端发送消息

         导包

    <!--websocket-->
    <dependency>
       <groupId>javax.websocket</groupId>
       <artifactId>javax.websocket-api</artifactId>
       <version>1.1</version>
       <scope>provided</scope>
    </dependency>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    其实只要下面那个就可以了,没用springBoot的话就用上面那个

    创建类WebSocket
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    @ServerEndpoint("/webSocket/{username}")
    @Component
    public class WebSocket {
        private static int onlineCount = 0;
        private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
        private Session session;
        private String username;
    
        //连接打开时执行
        @OnOpen
        public void onOpen(@PathParam("username") String username, Session session) throws IOException {
    
            this.username = username;
            this.session = session;
    
            addOnlineCount();
            clients.put(username, this);
            System.out.println("已连接");
        }
    
        //连接关闭时执行
        @OnClose
        public void onClose() throws IOException {
            clients.remove(username);
            subOnlineCount();
        }
    
        //收到消息时执行
        @OnMessage
        public void onMessage(String message) throws IOException {
    
            JSONObject jsonTo = JSONObject.parseObject(message);
            String mes = (String) jsonTo.get("message");
    
            if (!jsonTo.get("To").equals("All")){
                sendMessageTo(mes, jsonTo.get("To").toString());
            }else{
                sendMessageAll("给所有人");
            }
        }
    
        //连接错误时执行
        @OnError
        public void onError(Session session, Throwable error) {
            error.printStackTrace();
        }
    
        public void sendMessageTo(String message, String To) throws IOException {
            for (WebSocket item : clients.values()) {
                if (item.username.equals(To) )
                    item.session.getAsyncRemote().sendText(message);
            }
        }
    
        public void sendMessageAll(String message) throws IOException {
            for (WebSocket item : clients.values()) {
                item.session.getAsyncRemote().sendText(message);
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            WebSocket.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            WebSocket.onlineCount--;
        }
    
        public static synchronized Map<String, WebSocket> getClients() {
            return clients;
        }
    }

    进行配置
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    @Configuration
    public class WebSocketConfig {
    
        /**
         * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
    }

    后端方法发送消息时的代码
            WebSocket ws = new WebSocket();
            JSONObject jo = new JSONObject();
            jo.put("message", "我是后端,收到这个就说明成功了。");
            jo.put("To", "admin");
            try {
                ws.onMessage(jo.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } 
    顺便附一个前端工程方便后端写的时候调试
    https://files-cdn.cnblogs.com/files/best/WebSocketClient.rar
  • 相关阅读:
    IIT(ISM) Virtual Farewell E Dictator's plan for Valentine's day! 二分
    HDU
    LightOJ
    HDU 4407 Sum 容斥原理
    HDU 4686 Arc of Dream 矩阵快速幂
    uoj418
    Gym101237C The Palindrome Extraction Manacher
    Codeforces 100032 K
    codechef Suffix Palindromes
    Codeforces 932G Palindrome Partition
  • 原文地址:https://www.cnblogs.com/IceBlueBrother/p/14790381.html
Copyright © 2011-2022 走看看