pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
websocket配置:
package com.websocket.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { /** * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
Endpoint接收websocket链接:
package com.websocket.endpoint; import com.websocket.bean.SessionContext; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; @Slf4j @ServerEndpoint(value = "/test/{param}") @Component public class CustomWebSocket { private static AtomicInteger onlineCount = new AtomicInteger(0); public static Map<String, SessionContext> clients = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("param") String param) { String queryString = session.getQueryString(); System.out.println("param is :" + param); System.out.println("queryString is = " + queryString); onlineCount.incrementAndGet(); // 在线数加1 clients.put(session.getId(), SessionContext.newInstance(session, param)); log.info("有新连接加入:{},当前在线数为:{}", session.getId(), onlineCount.get()); } @OnClose public void onClose(Session session) { onlineCount.decrementAndGet(); // 在线数减1 clients.remove(session.getId()); log.info("有一连接关闭:{},当前在线数为:{}", session.getId(), onlineCount.get()); } @OnMessage public void onMessage(String message, Session session) { log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message); } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } }
定时轮询为每个链接发送数据:
package com.websocket; import com.websocket.endpoint.CustomWebSocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @EnableScheduling @SpringBootApplication public class WebsocketApplication { public static void main(String[] args) { SpringApplication.run(WebsocketApplication.class, args); } @Scheduled(cron = "*/2 * * * * *") public void run() { CustomWebSocket.clients.forEach((k, v)->{ try { v.getSession().getBasicRemote().sendText(v.getParam()+" send @"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } catch (IOException e) { e.printStackTrace(); } }); } }
因为要保存websocket建立连接的参数,所以CustomWebSocket.clients这个map中的value被一个java对象包裹了。
package com.websocket.bean; import lombok.Getter; import lombok.Setter; import javax.websocket.Session; @Getter @Setter public class SessionContext { private Session session; private String param; public static SessionContext newInstance(Session session) { SessionContext ctx = new SessionContext(); ctx.setSession(session); return ctx; } public static SessionContext newInstance(Session session,String param) { SessionContext ctx = new SessionContext(); ctx.setSession(session); ctx.setParam(param); return ctx; } }
启动服务并测试,测试用这个在线客户端
原文:https://www.cnblogs.com/luohaonan/p/13575156.html