package com.example.telecomproject.webController;
import com.example.telecomproject.dao.WebSocketService;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketCorsConfig implements WebSocketConfigurer {
private final WebSocketService webSocketService = new WebSocketService();
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketService, "/websocket").setAllowedOrigins("*");
}
}
定义一个WebSocketCorsConfig类实现接口
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class WebSocketService extends TextWebSocketHandler {
private static Set<WebSocketSession> clients = new HashSet<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
clients.add(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
clients.remove(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理从客户端接收的消息
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// 处理传输错误
}
public void sendMessage(float[] data) {
String json = convertArrayToJson(data);
for (WebSocketSession client : clients) {
try {
client.sendMessage(new TextMessage(json));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String convertArrayToJson(float[] array) {
// 将数组转换为JSON字符串
StringBuilder sb = new StringBuilder();
sb.append("["); // 开始数组
for (int i = 0; i < array.length; i++) {
sb.append(array[i]); // 添加数组元素的值
if (i < array.length - 1) { // 如果不是最后一个元素,则添加逗号
sb.append(",");
}
}
sb.append("]"); // 结束数组
return sb.toString();
}
}
发送的是一个字符串数组
@Scheduled(fixedRate = 5000)
public void performTask() {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
float[] processData = {60,60,3,34,2,50,40,60};
WebSocketService webSocketService = new WebSocketService();
webSocketService.sendMessage(processData);
}
控制器内使用@Scheduled(fixedRate = 5000)来执行定时任务
使用@Scheduled注解时在在启动器内添加允许定时器任务工作
@SpringBootApplication
@EnableScheduling
public class TelecomProjectApplication {
public static void main(String[] args) {
SpringApplication.run(TelecomProjectApplication.class, args);
}
}
加一个@EnableScheduling注解