• 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')
    }
    
  • 相关阅读:
    JavaScript 格式化数字
    浅析C#中单点登录的原理和使用
    从银行转账失败到分布式事务:总结与思考
    计算机网络资料
    阿里巴巴Java开发规约插件p3c详细教程及使用感受
    程序员如何打造属于自己的云笔记服务
    sql server2016里面的json功能
    mac pro 开启三只滑动选中文本
    技术网站
    idea gradle项目导入
  • 原文地址:https://www.cnblogs.com/luguojun/p/16132773.html
Copyright © 2020-2023  润新知