YYC
2023-10-19 723f54708d7c2b71f916e40952ebc818629e66ab
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package com.ld.igds.websocket;
 
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
 
import lombok.extern.slf4j.Slf4j;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
 
import com.alibaba.fastjson.JSONObject;
 
/**
 * WEB-Socket服务,该服务用于整个系统,包括大屏,粮情检测页面,气体操作页面
 * 
 * @author jiazx
 * 
 *         请求路径定义:"/websocket/{库区编码}/{业务代码}/{自定义标签}/{用户ID}"
 * 
 *         说明:通知以bizType为单位进行推送,同一个bizType接到相同的推送信息
 *
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{deptId}/{bizType}/{bizTag}/{userId}")
public class WebSocketServer {
 
    private static Map<String, Session> sessionPool = new ConcurrentHashMap<>();
    private static Map<String, String> sessionIds = new ConcurrentHashMap<>();
    
    /**
     * 配置模块在线状态
     */
    public static Map<String,Boolean> contextOnLineMap = new HashMap<String, Boolean>();
 
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
 
    @OnOpen
    public void onOpen(Session session,
            @PathParam("deptId") String deptId,
            @PathParam("bizType") String bizType,
            @PathParam("bizTag") String bizTag,
            @PathParam("userId") String userId) throws Exception {
 
        this.session = session;
 
        String key = deptId + "-" + bizType + "-" + bizTag + "-" + userId;
 
        sessionPool.put(key, session);
        sessionIds.put(session.getId(), key);
 
        log.info("new webSocket,key={}", key);
    }
 
    @OnClose
    public void onClose() {
        String key = sessionIds.get(session.getId());
 
        sessionPool.remove(key);
        sessionIds.remove(session.getId());
 
        log.info("WebSocket连接关闭={}", key);
        
        String bizType = key.split("-")[2];
        
        contextOnLineMap.put(bizType, false);
    }
 
    /**
     * 收到前端发送的信息
     * 
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
 
        contextOnLineMap.put(message,true);
 
        log.info("来自客户端信息:\n" + message);
    }
 
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
 
        String key = sessionIds.get(session.getId());
 
        sessionPool.remove(key);
        sessionIds.remove(session.getId());
        error.printStackTrace();
    }
 
    /**
     * 后端向前端推送信息,接受者为同一个业务类型操作所有人员
     * 
     * @param packet
     */
    public static void sendByPocket(WebSocketPacket packet) {
        if (StringUtils.isEmpty(packet.getBizType())) {
            log.error("WebSocket信息推送失败,业务类型不可为空。");
            return;
        }
 
        String tag = packet.getDeptId() + "-" + packet.getBizType() + "-" + packet.getBizTag();
 
        // 遍历推送,只要是bizType一致的均推送
        Session session;
        for (String key : sessionPool.keySet()) {
            if (key.indexOf(tag) != -1) {
                session = sessionPool.get(key);
                session.getAsyncRemote().sendText(
                        JSONObject.toJSONString(packet));
            }
        }
    }
 
    /**
     * 发送给指定人员
     * 
     * @param packet
     */
    public static void sendByUser(WebSocketPacket packet) {
        if (StringUtils.isEmpty(packet.getBizType())
                || StringUtils.isEmpty(packet.getDeptId())
                || StringUtils.isEmpty(packet.getUserId())) {
            log.error("WebSocket信息推送失败,组织编码和业务类型或者指定人信息参数没有获取到!");
 
            return;
        }
 
        String tag = packet.getDeptId() + "-" + packet.getBizType() + "-"
                + packet.getBizTag() + "-" + packet.getUserId();
 
        Session session;
        for (String key : sessionPool.keySet()) {
            if (tag.equals(key)) {
                session = sessionPool.get(key);
                session.getAsyncRemote().sendText(
                        JSONObject.toJSONString(packet));
            }
        }
    }
 
    /**
     * 根据指定的BizId标签推送
     *
     * @param packet
     */
    public static void sendByBizTag(WebSocketPacket packet) {
        if (StringUtils.isEmpty(packet.getBizType())
                || StringUtils.isEmpty(packet.getDeptId())
                || StringUtils.isEmpty(packet.getBizTag())) {
            log.error("WebSocket信息推送失败,组织编码和业务类型或者指定人信息参数没有获取到!");
 
            return;
        }
 
        String tag = packet.getDeptId() + "-" + packet.getBizType() + "-" + packet.getBizTag();
 
        // 遍历推送,只要是bizType一致的均推送
        Session session;
        for (String key : sessionPool.keySet()) {
            if (key.indexOf(tag) != -1) {
                session = sessionPool.get(key);
                session.getAsyncRemote().sendText(
                        JSONObject.toJSONString(packet));
            }
        }
 
    }
}