SpringBoot中websocket向前端发送实时数据

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注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值