whycxzp
2021-04-15 2ace24c7e9b3c493910841bdfc7e883c20a24c2b
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
package com.whyc.ws;
 
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
 
@ServerEndpoint(value = "/device", encoders = WebSocketEncoder.class)
@Component
@Api(tags = "设备ws")
@Slf4j
public class DeviceWebSocket {
 
    private Session session;
 
    private volatile Thread thread;
 
    @OnOpen
    public void onOpen(Session session) {
        log.warn("socket会话开启了:{}",session);
        this.session = session;
    }
 
    @OnMessage
    public void onMessage(String message) {
        try {
            this.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private void sendMessage(String message) {
        if(session!=null) {
            thread = new Thread("Thread_device") {
                public void run() {
                    while (!thread.isInterrupted()) {
                        try {
                            if (session.isOpen()) {
                                //session.getBasicRemote().sendObject("1");
                                session.getBasicRemote().sendObject(new Object());
                            }
                            sleep(1000);
                        } catch (IOException | InterruptedException | EncodeException e) {
                            interrupt();
                        }
                    }
                }
            };
            thread.start();
        }
    }
 
    @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();
        }
    }
 
}