kaiyu
2021-06-16 dc3e39dfbc7f99e2dd865c0f8274647c00bc5c70
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
package com.moral.api.websocket;
 
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
 
/**
 * @ClassName SingleDeviceServer
 * @Description TODO
 * @Author 陈凯裕
 * @Date 2021/6/15 13:56
 * @Version TODO
 **/
@ServerEndpoint("/singleDevice/{mac}")
@Component
public class SingleDeviceServer {
 
    //线程安全集合,用于存放server对象
    public static CopyOnWriteArraySet<SingleDeviceServer> sockets = new CopyOnWriteArraySet<>();
 
    private Session session;
 
    private String mac;
 
    @OnOpen
    public void onOpen(Session session, @PathParam("mac") String mac) throws Exception {
        this.session = session;
        this.mac = mac;
        sockets.add(this);
        System.out.println(mac);
    }
 
    @OnClose
    public void onClose() {
        sockets.remove(this);
    }
 
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(message);
    }
 
    @OnError
    public void onError(Session session, Throwable error) {
    }
 
    public void sendMessage(String message) throws Exception {
        if (this.session.isOpen()) {
            synchronized (session) {
                this.session.getBasicRemote().sendText(message);
            }
        }
    }
 
 
}