• 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();
        }
    }
    

    websocket服务端点

    @ServerEndpoint("/ws/test/{username}")
    @Component
    public class TestEndpoint {
    
        static final Logger loggger = LoggerFactory.getLogger(TestEndpoint.class);
        private static int onlineCount = 0;
        // 用来存放每个客户端对应的MyWebSocket对象。
        private static ConcurrentHashMap<String, TestEndpoint> webSocketMap = new ConcurrentHashMap<>();
        // 与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
        // 接收username
        private String username = "";
    
        // 发送自定义消息
        public static void sendInfo(String message, String username) {
            loggger.info("发送消息到:" + username + ",报文:" + message);
            if (StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)) {
                try {
                    webSocketMap.get(username).sendMessage(message);
                } catch (Exception e) {
                    loggger.error(e.getMessage(), e);
                }
            } else {
                loggger.error("用户" + username + ",不在线!");
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            TestEndpoint.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            TestEndpoint.onlineCount--;
        }
    
        // 打开连接
        @OnOpen
        public void onOpen(Session session, @PathParam("username") String username) {
            this.session = session;
            this.username = username;
            if (webSocketMap.containsKey(username)) {
                webSocketMap.remove(username);
                webSocketMap.put(username, this);
            } else {
                webSocketMap.put(username, this);
                addOnlineCount();
            }
    
            loggger.info("用户连接:" + username + ",当前在线人数为:" + getOnlineCount());
    
            try {
                sendMessage("连接成功");
            } catch (IOException e) {
                loggger.error("用户:" + username + ",网络异常!!!!!!");
            }
        }
    
        // 关闭连接
        @OnClose
        public void onClose() {
            if (webSocketMap.containsKey(username)) {
                webSocketMap.remove(username);
                subOnlineCount();
            }
            loggger.info("用户退出:" + username + ",当前在线人数为:" + getOnlineCount());
        }
    
        // 接收消息
        @OnMessage
        public void onMessage(String message, Session session) {
            loggger.info("用户消息:" + username + ",报文:" + message);
        }
    
        @OnError
        public void onError(Session session, Throwable error) {
            loggger.error("用户错误:" + this.username + ",原因:" + error.getMessage());
            error.printStackTrace();
        }
    
        // 推送消息
        public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
        }
    }
    

    客户端

    var webSocket = null;
    if ('WebSocket' in window) {
        webSocket = new WebSocket('ws://serverhost/ws/test/username');
    	// 接收消息
    	webSocket.onmessage = function (event) {
    	    // event.data;
    	}	
    	// 关闭连接
    	webSocket.onclose = function () {
    	}
    	webSocket.onerror = function () {    
    	}
    	// 打开连接
    	webSocket.onopen = function () {
    		// 发送消息
    	    var message = "msgfromclient";
    	    webSocket.send(message);
    	}
    } else {
        alert('Not support websocket')
    }
    
  • 相关阅读:
    python调用linux DBus
    python查看单个应用的内存
    Azkaban
    H2 数据库引擎
    【IDEA与sql执行计划】
    【用draw.io 绘制ER图,非鸭蛋型ER图~】
    MySQL&Oracle数据库进阶学习【未完】
    【关于Typora 在线图床配置】
    什么是文件描述符
    同步个人vs code 习惯性配置 到码云(Gitee)
  • 原文地址:https://www.cnblogs.com/luguojun/p/14294708.html
Copyright © 2020-2023  润新知