jiazx0107@163.com
2023-11-09 97c75a868e9fca03598dfa862bdd7ad94fd5fdcb
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
package com.fzzy.gateway.hx2023.websocket;
 
import com.alibaba.fastjson.JSONObject;
import com.fzzy.gateway.GatewayUtils;
import com.fzzy.gateway.hx2023.data.WebSocketPacket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * 基于前端 websocket 订阅地磅数据 topic:
 */
@Slf4j
@Component
@ServerEndpoint(value = "/device/{productId}/{deviceId}/message/property/report")
public class WebSocketDeviceReport {
 
    private static Map<String, Session> sessionPool = new ConcurrentHashMap<>();
    private static Map<String, String> sessionIds = new ConcurrentHashMap<>();
 
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
 
 
    @OnOpen
    public void onOpen(Session session,
                       @PathParam("productId") String productId,
                       @PathParam("deviceId") String deviceId,
                       @PathParam("clientId") String clientId
    ) throws Exception {
 
        this.session = session;
 
        String key = productId + "-" + deviceId;
 
        sessionPool.put(key, session);
        sessionIds.put(session.getId(), key);
 
        GatewayUtils.updateOnline(deviceId);
 
        log.info("new webSocket,clientId={}", key);
    }
 
    @OnClose
    public void onClose() {
 
        String key = sessionIds.get(session.getId());
 
        String deviceId = key.substring(key.indexOf("-"));
 
        GatewayUtils.updateOffOnline(deviceId);
 
        sessionPool.remove(key);
        sessionIds.remove(session.getId());
 
        log.info("WebSocket连接关闭={}", key);
 
    }
 
    /**
     * 收到前端发送的信息
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
 
        log.info("来自客户端信息:\n" + message);
    }
 
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
 
        String key = sessionIds.get(session.getId());
 
        String deviceId = key.substring(key.indexOf("-"));
 
        GatewayUtils.updateOffOnline(deviceId);
 
        sessionPool.remove(key);
        sessionIds.remove(session.getId());
        error.printStackTrace();
    }
 
 
    /**
     * 推送信息到前端
     *
     * @param packet
     */
    public void sendByPacket(WebSocketPacket packet) {
        if (StringUtils.isEmpty(packet.getDeviceId())) {
            log.error("WebSocket信息推送失败,设备编码为空。");
            return;
        }
 
        String tag = packet.getDeviceId();
 
        // 遍历推送
        Session session;
        String productId;
        for (String key : sessionPool.keySet()) {
 
            productId = key.substring(0, key.indexOf("-"));
 
            packet.getHeaders().setProductId(productId);
 
            log.debug("----------websocket返回信息-----{}", packet);
 
            if (key.indexOf(tag) != -1) {
                session = sessionPool.get(key);
                session.getAsyncRemote().sendText(JSONObject.toJSONString(packet));
            }
        }
    }
 
 
}