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);
|
}
|
}
|
}
|
|
|
}
|