• java:springboot 整理webSocket


    1、配置WebSocketConfig 类

    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    
    @Configuration
    @EnableWebSocket
    public class WebSocketConfig {
    
        //如果需要引用service
        // @Autowired
        // public void socketAppTokenService(AppTokenService appTokenService) {
        //    WebSocketUtil.appTokenService = appTokenService;
        // }
    
    
        /**
         * 服务器节点
         *
         * @return
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    2、编写WebSocketUtil

    import cn.hutool.json.JSONUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    @Slf4j
    @ServerEndpoint("/ws")
    @Component
    public class WebSocketUtil {
    
        private static int onlineCount = 0;//在线人数
        private static CopyOnWriteArrayList<WebSocketUtil> webSocketSet = new CopyOnWriteArrayList<WebSocketUtil>();//在线用户集合
        private Session session;//与某个客户端的连接会话
        private String currentUser;
    	
    	//如果需要引用service
        //public static AppTokenService appTokenService;
    
        @OnOpen
        public void onOpen(Session session) {
            this.session = session;
            webSocketSet.add(this);//加入set中
            addOnlineCount();
            System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
            allCurrentOnline();
        }
    
        @OnClose
        public void onClose() {
            webSocketSet.remove(this);
            subOnlineCount();
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
            allCurrentOnline();
        }
    
        @OnMessage
        public void onMessage(String message, Session session) {
            log.info("来自客户端的消息:" + message);
            for (WebSocketUtil item : webSocketSet) {
                try {
                     //编写业务
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
    
            }
        }
    
        @OnError
        public void onError(Session session, Throwable throwable) {
            System.out.println("发生错误!");
            throwable.printStackTrace();
        }
    
        public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
        }
    
        /**
         * 获取当前所有在线用户名
         */
        public static void allCurrentOnline() {
            for (WebSocketUtil item : webSocketSet) {
                System.out.println(item.currentUser);
            }
        }
    
        /**
         * 发送给指定用户
         */
        public static void sendMessageTo(String message, String token) throws IOException {
            for (WebSocketUtil item : webSocketSet) {
                if (item.currentUser.equals(token)) {
                    System.out.println("token:" + message);
                    item.session.getBasicRemote().sendText(message);
                }
            }
        }
    
        /**
         * 群发自定义消息
         */
        public static void sendInfo(String message) throws IOException {
            System.out.println(message);
            for (WebSocketUtil item : webSocketSet) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    continue;
                }
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            WebSocketUtil.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            WebSocketUtil.onlineCount--;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109

    3、

    @Slf4j
    @RestController
    public class WebSocketController {
    
        //给指定用户发
        @LoginIgnore
        @GetMapping("/send/{token}/{message}")
        public R sendMessage(@PathVariable("message") String message, @PathVariable("token") String token) throws IOException {
        WebSocketUtil.sendMessageTo(message,token)
            return R.ok();
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4、HTML测试

    DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Netty-Websockettitle>
        <script type="text/javascript">
            var socket;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {
            	//换成你的地址
                socket = new WebSocket("ws://127.0.0.1:9331/ws");
                socket.onmessage = function (event) {
                    var ta = document.getElementById('responseText');
                    let resData = JSON.parse(event.data);
                    console.log(resData);
                    ta.value += "消息: " + resData.proxy + "\t\t消息: " + resData.data + "\r\n";
                };
                socket.onopen = function (event) {
                    var ta = document.getElementById('responseText');
                    ta.value = "Netty-WebSocket服务器。。。。。。连接  \r\n";
                };
                socket.onclose = function (event) {
                    var ta = document.getElementById('responseText');
                    ta.value = "Netty-WebSocket服务器。。。。。。关闭 \r\n";
                };
            } else {
                alert("您的浏览器不支持WebSocket协议!");
            }
    
            function send(proxy,token,data) {
                if (!window.WebSocket) {
                    return;
                }
                let param={
    				proxy: proxy,
                    token: token,
                    data: data
                }
                if (socket.readyState == WebSocket.OPEN) {
                    let resData = JSON.stringify(param);
                    console.log(resData);
                    socket.send(resData);
                } else {
                    alert("WebSocket 连接没有建立成功!");
                }
    
            }
    
        script>
    head>
    <body>
    <form onSubmit="return false;">
        <div>
            <label>proxylabel><input type="text" name="proxy" value="${proxy!!}"/> <br/>
    		 <label>tokenlabel><input type="text" name="token" value="${token!!}"/> <br/>
            <label>datalabel><input type="text" name="data" value="这里输入数据"/> <br/>
            <br/> <input type="button" value="发送ws消息"
                         onClick="send(this.form.proxy.value, this.form.token.value,this.form.data.value)"/>
        div>
        <hr color="black"/>
        <h3>服务端返回的应答消息h3>
        <textarea id="responseText" style="width: 1024px;height: 300px;">textarea>
    form>
    body>
    html> 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
  • 相关阅读:
    2024中国北京国际大健康产业博览会,引领健康产业发展的盛会
    dedecms织梦快照被挟持和篡改入侵漏洞修复
    你以为键入网址后只是等待吗?惊!原来网页显示背后隐藏着这些奇妙步骤(中)
    高级运维学习(十四)Zabbix监控(一)
    Kibana Query Language (KQL)
    是谁还没听过杨氏矩阵~原理和实现代码都已经准备好了
    动态规划:13目标和
    cmake简洁教程 - 第五篇
    MySQL 创建和管理表
    java和vue开发的电子书系统自动检测敏感词小说网站
  • 原文地址:https://blog.csdn.net/bei_FengBoby/article/details/127982266