ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 1. 定时推送给所有人 实现步骤如下: **1. 启动类上标注注解`@EnableScheduling`开启定时服务** ```java @EnableScheduling @SpringBootApplication public class SocketApplication { public static void main(String[] args) { SpringApplication.run(SocketApplication.class, args); } } ``` **2. 方法上标注注解`@Scheduled`开始定时任务** ```java @Component @ServerEndpoint(value = "/v1/scheduled") public class ScheduledController { /** * 存储每一个用户的Session */ private final static Map<String, Session> onlineUsers = new HashMap<>(1); @OnOpen public void open(Session session) { //当用户连接进来时存储每一个用户的Session onlineUsers.put(session.getId(), session); } //每3s钟推送一次 @Scheduled(fixedRate = 3000) public void broadcastAllUsers() { for (Map.Entry<String, Session> entry : onlineUsers.entrySet()) { entry.getValue().getAsyncRemote().sendText("定时推送给所有人."); } } } ``` **3. 前端代码** ```js var socket = null function connect() { if (socket == null) { socket = new WebSocket('ws://localhost:8090/v1/scheduled') socket.onmessage = (e) => { console.info(e.data) } } } ```