liurunyu
2025-02-11 f717ad3e0a712e823d61383f42de6faf917e7636
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.dy.pipIrrRemote.largeScreen;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @Author: liurunyu
 * @Date: 2025/2/10 15:25
 * @Description 客户端(浏览器)每建立一个websocket连接,服务端就会创建一个WebSocketServer实例
 */
@Slf4j
@ServerEndpoint("/websocket/ls/{id}")
@Component
public class WebSocketServer {
 
    // 静态变量,记录当前在线连接数
    private static int onlineCount = 0;
 
    // 存放每个客户端对应的WebSocketServer对象
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
 
    // 客户端连接会话,通过它给客户端发送数据
    private Session session;
 
    // 客户端id
    private String id = "";
 
    /**
     * 连接建立成功调用的方法
     * @param session websocket会话对象
     * @param id 客户端id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        this.id = id;
        if(this.id == null || this.id.length() == 0){
            this.id = "" + System.nanoTime() ;
        }
        this.sendMessage(WebSocketHeartBeat.getHeartBeatMessage());
 
        if (webSocketMap.containsKey(id)) {
            webSocketMap.remove(id);
            webSocketMap.put(id, this);
        } else {
            webSocketMap.put(id, this);
            WebSocketServer.addOnlineCount();
        }
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(id)) {
            webSocketMap.remove(id);
            //从set中删除
            WebSocketServer.subOnlineCount();
        }
        log.info("客户端:" + id + ",关闭了websocket");
    }
 
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("客户端:" + id + ",websocket报文:" + message);
    }
 
    /**
     * 会话异常
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("客户端:" + this.id + ",websocket会话异常,原因:" + error.getMessage());
    }
 
    /**
     * 服务器主动推送消息
     */
    public void sendMessage(String message) {
        try{
            this.session.getBasicRemote().sendText(message);
        }catch (Exception e){
            log.error("客户端:" + id + ",websocket网络发送数据异常", e);
        }
    }
 
    /**
     * 服务器主动群推送消息
     */
    public static void sendAllMessage(String message) throws IOException {
        ConcurrentHashMap.KeySetView<String, WebSocketServer> ids = webSocketMap.keySet();
        for (String id : ids) {
            WebSocketServer webSocketServer = webSocketMap.get(id);
            webSocketServer.sendMessage(message);
        }
    }
 
    /**
     * 服务器指定客户端推送消息
     */
    public static void sendOneMessage(String message, String id) throws IOException {
        if (message != null && message.length() != 0 && webSocketMap.containsKey(id)) {
            webSocketMap.get(id).sendMessage(message);
        } else {
            log.error("客户端" + id + ",不在线!");
        }
    }
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
 
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}