package com.whyc.webSocket;
|
|
import com.whyc.service.PwrdevAcdcdataService;
|
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;
|
|
@Component
|
@ServerEndpoint(value = "/powerRT",encoders = WebSocketEncoder.class)
|
public class PowerRTSocket {
|
|
private volatile Thread thread;
|
|
private static final int executeTime = 15000;
|
|
private static PwrdevAcdcdataService service;
|
|
@Autowired
|
public void setService(PwrdevAcdcdataService service) {
|
PowerRTSocket.service = service;
|
}
|
|
@OnMessage
|
public void onMessage(Session session, String deviceId){
|
thread = new Thread("Thread_PowerRT") {
|
public void run() {
|
while (!thread.isInterrupted()) {
|
try {
|
if (session.isOpen()) {
|
session.getBasicRemote().sendObject(service.getPowerInfoById2(Integer.parseInt(deviceId)));
|
}
|
sleep(executeTime);
|
} catch (IOException | InterruptedException | EncodeException e) {
|
interrupt();
|
}
|
}
|
}
|
};
|
thread.start();
|
}
|
|
@OnClose
|
public void onClose(){
|
if (thread != null && thread.isAlive()) {
|
thread.interrupt();
|
}
|
}
|
|
@OnError
|
public void onError(Throwable error) {
|
error.printStackTrace();
|
if (thread != null && thread.isAlive()) {
|
thread.interrupt();
|
}
|
}
|
}
|