# WebSocket

可实现后端主动通知前端,推送消息。


背景:如下图,绿色代表正常,红色代表异常。我们刚开始全都是正常,然后让id=3得用户提交状态,服务端主动通知页面,状态变为异常

O58nYD.png

# WebSocket前端
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时监控</title>
    <style>
        .item {
            display: flex;
            border-bottom: 1px solid #000000;
            justify-content: space-between;
            width: 30%;
            line-height: 50px;
            height: 50px;
        }

        .item span:nth-child(2) {
            margin-right: 10px;
            margin-top: 15px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #55ff00;
        }

        .nowI {
            background: #ff0000 !important;
        }
    </style>
</head>

<body>
    <div id="app">
        <div v-for="item in list" class="item">
            <span>{{item.id}}.{{item.name}}</span>
            <span :class='item.state==-1?"nowI":""'></span>
        </div>
    </div>

    <!-- 生产环境版本,优化了尺寸和速度 -->
    <script src="./js/vue.min.js"></script>
    <script type="text/javascript">
        //vue 实列
        var app = new Vue({
            el: "#app",
            data: {
                list: [
                    {id: 1, name: "刘备", state: 1},
                    {id: 2, name: "关羽", state: 1},
                    {id: 3, name: "张飞", state: 1},
                    {id: 4, name: "诸葛亮", state: 1},
                    {id: 5, name: "孙权", state: 1},
                ],
            },
        })

        
        var webSocket = null;
        if ('WebSocket' in window) {
            // 1. 创建 WebSocket
            webSocket = new WebSocket("ws://localhost:18801/webSocket/" + getUUID());

            // 2. 连接 WebSocket
            webSocket.open = function () {
                console.log("WebSocket 已连接");
                webSocket.send("消息发送测试")
            }

            //3. 接收到消息
            webSocket.onmessage = function(msg) {
                var serverMsg = msg.data;
                var t_id = parseInt(serverMsg) //服务端发过来的消息,string需转化为int类型
                for(let i = 0; i < app.list.length; i++) {
                    let item = app.list[i];
                    if(item.id == t_id) {
                        item.state = -1;
                        app.list.splice(i, 1, item)
                        break;
                    }
                }
            }

            //4. 关闭事件
            webSocket.onclose = function() {
                console.log("websocket已关闭");
            };

            //5. 发生了错误事件
            webSocket.onerror = function(err) {
                console.log("websocket发生了错误" + err);
            }
        } else {
            alert("很遗憾,您的浏览器不支持WebSocket!")
        }

        
        // 获取唯一的UUID
        function getUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c){
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    </script>
</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
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
110
# WebSocket+SpringBoot后端
  1. springboot 选择 Spring Web + WebSocket 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9

项目结构

websocket-demo
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.biubiu.websocket
│   │   │       ├── config
│   │   │       │   └── WebSocketConfig.java
│   │   │       ├── controller
│   │   │       │   └── WebSocketController.java
│   │   │       ├── service
│   │   │       │   └── WebSocketService.java
│   │   │       └── Application.java
│   │   └── resources
│   │       └── application.yml
│   └── test
└── pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  1. 配置
server.port: 18801
mySocket.myPwd: jae_123
1
2
  1. WebSocketConfig配置类
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
1
2
3
4
5
6
7
  1. WebSocketServer 是请求的处理类。作用相当于HTTP请求中的controller
@Component
@ServerEndpoint("/webSocket/{uid}")
public class WebSocketServer {
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static final AtomicInteger ON_LINE_NUM = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的 WebSocketServer对象。
     */
    private static CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<Session>();

    /**
     * 有客户端连接成功
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String uid) {
        sessionPools.add(session);
        ON_LINE_NUM.incrementAndGet();
        log.info(uid + "加入webSocket!当前在线人数为" + ON_LINE_NUM);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("接收到消息:" + message);
    }
    @OnMessage
    public void onMessage(byte[] message) throws IOException{
        String msg = new String(message, StandardCharsets.UTF_8);
        log.info("webSocket后台收到消息:" + msg);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        int cnt = ON_LINE_NUM.decrementAndGet();
        log.info("有连接关闭,当前连接数为:{}", cnt);
    }

    /**
     * 发送消息
     */
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 群发消息
     */
    public void broadCastInfo(String message) throws IOException {
        for (Session session : sessionPools) {
            if(session.isOpen()){
                sendMessage(session, message);
            }
        }
    }

    /**
     * 发生错误
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生错误");
        throwable.printStackTrace();
    }
}
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
  1. WebSocketController类,用于进行接口测试
@RestController
@RequestMapping("/open/socket")
public class WebSocketController {

    @Value("${mySocket.myPwd}")
    public String myPwd;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 手机客户端请求接口
     *
     * @param id  发生异常的设备ID
     * @param pwd 密码(实际开发记得加密)
     */
    @GetMapping(value = "/onReceive")
    public void onReceive(String id, String pwd) throws IOException {
        //密码校验一致(这里举例,实际开发还要有个密码加密的校验的),则进行群发
        if (pwd.equals(myPwd)) {
            webSocketServer.broadCastInfo(id);
        }
    }

}
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
  1. 测试

打开前端页面 控制台显示

访问测试接口 http://localhost:18801/open/socket/onReceive?id=3&pwd=jae_123

注意id为3的这个数据的状态变化,实时通信成功