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