liuxiaolong
2019-05-06 0bc4f4c791437b39b8c30624f5c21f8c855dc61d
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package com.cloud.retrieve.service.impl;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloud.retrieve.filter.AuthNoneIgnore;
import com.cloud.retrieve.service.EsDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
@ServerEndpoint(value = "/alarmWebSocketServer/{userId}/{id}")
@Component
public class MyWebSocket {
 
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
 
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
 
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
 
    private Long picDate;
  /*  @Autowired
    private EsDataService esDataService;*/
    public static  EsDataService esDataService ;
 
    private HashMap<String,Object> curMap = new HashMap<>();
 
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
 
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            JSONObject alarmData = esDataService.findEsAllAlarmDataByPage(1, 200,null,null);
            alarmData.put("data", alarmData.getJSONArray("equList"));
            alarmData.remove("equList");
            alarmData.put("success", true);
            String s = alarmData.toJSONString();
            sendMessage(s);
            JSONArray equList = alarmData.getJSONArray("data");
 
            String dateStr = ((JSONObject)equList.get(equList.size()-1)).getString("picDate");
            try {
                this.picDate = sdf.parse(dateStr).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
//            this.picDate = Timestamp.valueOf(((JSONObject)equList.get(equList.size()-1)).getString("picDate"));
 
//            this.likeDate = ((JSONObject)equList.get(equList.size()-1)).getSqlDate("picDate");
        } catch (IOException e){
            System.out.println("IO异常;"+e);
        }
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
            webSocketSet.remove(this);  //从set中删除
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
        //群发消息
       /* for (MyWebSocket item : webSocketSet){
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }
 
    /**
     * 发生错误时调用
     * */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("推送数据发生错误");
        error.printStackTrace();
    }
 
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
 
    /**
     * 群发自定义消息
     * */
    public static void sendInfo() throws IOException {
        while(true){
            try {
                Thread.sleep(2000);
                JSONObject alarmData = esDataService.findEsAllAlarmDataByPage(1, 200,null,null);
                for (MyWebSocket item : webSocketSet){
                    try {
                        if((alarmData !=null && alarmData.get("total")!= null && Integer.parseInt(alarmData.getString("total")) > 0)){
                            JSONArray curAlarmList = alarmData.getJSONArray("equList");
                            List<Object> sendList = new ArrayList<>();
                            Long lastLikeDate = null;
                            if(item.picDate !=null){//socket获取过数据
                                lastLikeDate = item.picDate;
                                for(int i=0;i < curAlarmList.size();i++){
                                    JSONObject obj = (JSONObject) curAlarmList.get(i);
 
 
                                    Long sTime =null;
                                    try {
                                        sTime = sdf.parse(obj.getString("picDate")).getTime();
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
 
//                                    Long sTime = Timestamp.valueOf(obj.getString("picDate"));
//                                    Date sTime = obj.getSqlDate("likeDate");
                                    String recordId = obj.get("Id").toString();
                                    if(sTime > lastLikeDate && !item.curMap.containsKey(recordId)){
                                        item.curMap.put(recordId, obj);
                                        sendList.add(obj);
                                    }
                                }
                            }else{
                                for(int i=0;i < curAlarmList.size();i++){
                                    JSONObject obj = (JSONObject) curAlarmList.get(i);
                                    String recordId = obj.get("Id").toString();
                                    item.curMap.put(recordId, obj);
                                    sendList.add(obj);
                                }
                            }
                            if(sendList.size() > 0){
                                JSONObject sData = new JSONObject();
                                sData.put("total",alarmData.getString("total"));
                                sData.put("data", sendList);
                                sData.put("success", true);
                                if(sendList.size()<20)
                                    log.info("boot==ws推送es数据:"+sendList);
                                item.sendMessage(sData.toJSONString());
 
 
                                String dateStr = ((JSONObject)sendList.get(sendList.size()-1)).getString("picDate");
                                try {
//                                    log.info("picDate上次比对时间:"+sdf.parse(dateStr).getTime());
                                    item.picDate = sdf.parse(dateStr).getTime();
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
 
//                                Timestamp sTime = Timestamp.valueOf(((JSONObject)sendList.get(sendList.size()-1)).getString("picDate"));
//                                lastLikeDate = ((JSONObject)sendList.get(sendList.size()-1)).getSqlDate("likeDate");
//                                log.info("websocket推送es数据 startTime:"+lastLikeDate);
//                                item.picDate = lastLikeDate;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }
 
    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}