package com.whyc.websocket;
|
|
import com.whyc.service.BatteryRTService;
|
import lombok.extern.slf4j.Slf4j;
|
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;
|
|
@ServerEndpoint(value = "/battery/{method}/{userId}",encoders = WebSocketEncoder.class)
|
@Component
|
@Slf4j
|
public class BatteryRTWebSocket {
|
|
private Session session;
|
|
private static BatteryRTService service;
|
|
private volatile Thread thread;
|
|
private static final int executeTime = 4000;
|
|
@Autowired
|
public void setService(BatteryRTService service) {
|
BatteryRTWebSocket.service = service;
|
}
|
|
@OnOpen
|
public void onOpen(Session session, @PathParam("method") String method,@PathParam("userId")Integer userId){
|
|
switch (method) {
|
case "status": {
|
if (session != null) {
|
thread = new Thread("Thread_battery") {
|
public void run() {
|
while (!thread.isInterrupted()) {
|
try {
|
if (session.isOpen()) {
|
session.getBasicRemote().sendObject(service.getStatus(userId));
|
}
|
sleep(executeTime);
|
} catch (IOException | InterruptedException | EncodeException e) {
|
interrupt();
|
}
|
}
|
}
|
};
|
thread.start();
|
}
|
}
|
break;
|
}
|
|
}
|
|
@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();
|
}
|
}
|
|
}
|