You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
3.6 KiB
Java

package com.ipsplm.ws;
import com.ipsplm.service.simulation.ISimulationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/simulation")
public class SimulationWebsocket {
private Session session;
private static ISimulationService simulationService;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private boolean isSimulationRunning = false;
@Autowired
public void setService(ISimulationService simulationService) {
SimulationWebsocket.simulationService = simulationService;
}
//存放websocket的集合
private static CopyOnWriteArraySet<SimulationWebsocket> webSocketSet = new CopyOnWriteArraySet<>();
@OnOpen
public void OnOpen(Session session) {
this.session = session;
webSocketSet.add(this);
log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
}
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端发来的消息:{}", message);
if ("StartSimulation".equals(message)) {
//发送开始仿真的信息
String result = simulationService.getPlantData(message);
if ("Simulation Started".equals(result)) {
isSimulationRunning = true;
log.info("【仿真开始】");
scheduler.scheduleAtFixedRate(() -> {
if (isSimulationRunning) {
String data = simulationService.getPlantData("SimulationProgress");
// 根据需要处理和发送获取到的数据
log.info("【仿真数据】:" + data);
sendMessage(data);
if("1".equals(data) || "1.00".equals(data)){
sendMessage("ending");
isSimulationRunning = false;
scheduler.shutdown();
}
}
}, 0, 10, TimeUnit.SECONDS);
} else {
sendMessage("Simulation Start Failed");
}
} else if ("ResetSimulation".equals(message)) {
String resetSimulation = simulationService.getPlantData(message);
if ("Simulation Reset".equals(resetSimulation)) {
sendMessage("ending");
} else {
sendMessage("Simulation Reset Failed");
}
} else {
String resetSimulation = simulationService.getPlantData(message);
}
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
}
public void sendMessage(String message) {
for (SimulationWebsocket webSocket : webSocketSet) {
try {
synchronized (webSocket.session) {
if (webSocket.session.isOpen()) {
webSocket.session.getBasicRemote().sendText(message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}