whycxzp
2021-10-12 d5cf76188ad37f062f37ebce3464097203b4db05
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
package com.whyc.websocket;
 
import com.whyc.service.BatteryRTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
 
@ServerEndpoint(value = "/battery/{method}/{userId}",encoders = WebSocketEncoder.class)
@Component
@Slf4j
public class BatteryRTWebSocket {
 
    private Session session;
 
    private static BatteryRTService service;
 
    private volatile Thread thread;
 
    private static final int executeTime = 15000;
 
    @Autowired
    public void setService(BatteryRTService service) {
        BatteryRTWebSocket.service = service;
    }
 
    @OnOpen
    public void onOpen(Session session, @PathParam("method") String method,@PathParam("userId")Integer userId){
 
        switch (method) {
            case "status": {
                if (session != null) {
                    thread = new Thread("Thread_battery") {
                        public void run() {
                            while (!thread.isInterrupted()) {
                                try {
                                    if (session.isOpen()) {
                                        session.getBasicRemote().sendObject(service.getStatus(userId));
                                    }
                                    sleep(executeTime);
                                } catch (IOException | InterruptedException | EncodeException e) {
                                    interrupt();
                                }
                            }
                        }
                    };
                    thread.start();
                }
            }
            break;
        }
 
    }
 
    @OnClose
    public void onClose(){
        if (thread != null && thread.isAlive()) {
            thread.interrupt();
        }
        log.warn("webSocket会话关闭了:{}",session);
    }
 
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
        if (thread != null && thread.isAlive()) {
            thread.interrupt();
        }
    }
 
}