本文共 2754 字,大约阅读时间需要 9 分钟。
server: port: 18092
com.ct.tutorial com.ct 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket org.projectlombok lombok
org.springframework.boot spring-boot-starter-parent 2.5.0
/** * @Author LaoHa * @Date 2021/6/24 */@SpringBootApplicationpublic class AppWebSocket { public static void main(String[] args) { SpringApplication.run(AppWebSocket.class, args); }}
/** * @Author LaoHa * @Date 2021/6/24 */@Configurationpublic class WebSocketConfig { /** * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
/** * 前后端交互的类实现消息的接收推送(自己发送给自己) * * @ServerEndpoint(value = "/test/one") 前端通过此URI和后端交互,建立连接 */@Slf4j@ServerEndpoint(value = "/test/one")@Componentpublic class OneWebSocket { /** * 记录当前在线连接数 */ private static AtomicInteger onlineCount = new AtomicInteger(0); /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) { onlineCount.incrementAndGet(); // 在线数加1 log.info("有新连接加入:{},当前在线人数为:{}", session.getId(), onlineCount.get()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session) { onlineCount.decrementAndGet(); // 在线数减1 log.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message); this.sendMessage("Hello, " + message, session); } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } /** * 服务端发送消息给客户端 */ private void sendMessage(String message, Session toSession) { try { log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message); toSession.getBasicRemote().sendText("来自服务端的消息:"+message); } catch (Exception e) { log.error("服务端发送消息给客户端失败:{}", e); } }}
My WebSocket
服务端
浏览器
转载地址:http://qlmdi.baihongyu.com/