新版仿ok交易所-后端
zj
2025-01-06 6e21cf6973aa1898259ddceda665f0f1b06272ab
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.yami.trading.api.websocket;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * webSocket服务层 这里我们连接webSocket的时候,
 *
 * 路径中传一个参数值type,用来区分不同页面推送不同的数据
 *
 */
@ServerEndpoint(value = "/api/websocket/{type}/{param}")
@Slf4j
@Component
public class WebSocketServer {
 
    /**
     * 静态变量,用来记录当前在线连接数。
     *
     * 后面把它设计成线程安全的。
     */
    private static int onlineCount = 0;
 
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    public static ConcurrentHashMap<String, WebSocketSession> realtimeMap = new ConcurrentHashMap<String, WebSocketSession>();
    public static ConcurrentHashMap<String, WebSocketSession> tradeMap = new ConcurrentHashMap<String, WebSocketSession>();
    public static ConcurrentHashMap<String, WebSocketSession> depthMap = new ConcurrentHashMap<String, WebSocketSession>();
 
 
 
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "type") String type,
                       @PathParam(value = "param") String param, Session session) {
 
        WebSocketSession webSocketSession = new WebSocketSession(session,  getTimeInMillis(), type, param);
        // 加入set中
        if (WebSocketEnum.SOCKET_ENUM_REALTIME.getCode().equals(type)) {
            realtimeMap.put(session.getId(), webSocketSession);
        }else if (WebSocketEnum.SOCKET_ENUM_TRADE.getCode().equals(type)) {
            tradeMap.put(session.getId(), webSocketSession);
        }else if (WebSocketEnum.SOCKET_ENUM_DEPTH.getCode().equals(type)) {
            depthMap.put(session.getId(), webSocketSession);
        }
 
        // 在线数加1
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        log.info("有新连接加入!请求ID:{},当前在线人数为{}", webSocketSession.getSetKey(), getOnlineCount());
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "type") String type,
                        @PathParam(value = "param") String param, Session session) {
        String id = session.getId();
        String setKey = id + "_" + type + "_" + param;
        System.out.println("关闭连接的setKey:" + setKey);
        if (setKey != null && !"".equals(setKey)) {
            // 从set中删除
            if (WebSocketEnum.SOCKET_ENUM_REALTIME.getCode().equals(type)) {
                realtimeMap.remove(id);
            }else if (WebSocketEnum.SOCKET_ENUM_TRADE.getCode().equals(type)) {
                tradeMap.remove(id);
            }else if (WebSocketEnum.SOCKET_ENUM_DEPTH.getCode().equals(type)) {
                depthMap.remove(id);
            }
            // 在线数减1
            subOnlineCount();
            try {
                if (session != null) {
                    session.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("有一连接关闭!请求ID:"+ id + "当前在线人数为" + getOnlineCount());
            log.info("有一连接关闭!请求ID:{},当前在线人数为{}", setKey, getOnlineCount());
        }
    }
 
    @OnMessage
    public void onMessage(String message, Session session) {
        String sessionId = session.getId() ;
        if(realtimeMap.containsKey(sessionId)){
            realtimeMap.get(sessionId).setTimeStr(getTimeInMillis());
        }else if (tradeMap.containsKey(sessionId)){
            tradeMap.get(sessionId).setTimeStr(getTimeInMillis());
        }else if(depthMap.containsKey(sessionId)){
            depthMap.get(sessionId).setTimeStr(getTimeInMillis());
        }
    }
 
    /**
     * 发生错误时调用
     **/
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误:" + error);
        error.printStackTrace();
    }
 
 
    /**
     * 给指定的请求发送消息
     *
     */
    public static void sendToMessageById(String key, String message, String type) {
        try {
            if (WebSocketEnum.SOCKET_ENUM_REALTIME.getCode().equals(type)) {
                if (realtimeMap.get(key) != null) {
                    realtimeMap.get(key).sendMessage(message);
                } else {
                    System.out.println("realtimeMap中没有此key,不推送消息");
                }
            }else if (WebSocketEnum.SOCKET_ENUM_TRADE.getCode().equals(type)) {
                if (tradeMap.get(key) != null) {
                    tradeMap.get(key).sendMessage(message);
                } else {
                    System.out.println("tradeMap中没有此key,不推送消息");
                }
            }else if (WebSocketEnum.SOCKET_ENUM_DEPTH.getCode().equals(type)) {
                if (depthMap.get(key) != null) {
                    depthMap.get(key).sendMessage(message);
                } else {
                    System.out.println("depthMap中没有此key,不推送消息");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private static long getTimeInMillis() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.SECOND, c.get(Calendar.SECOND) + 60);
        return c.getTimeInMillis();
    }
 
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
 
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}