package com.ipsplm.websocket; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * @Description WebSocket处理类 * @Author FanDongqiang * @Date 2023/5/8 9:17 * @Version 1.0 */ @Component @Slf4j @ServerEndpoint("/websocket/test-token4") public class WebSocketHandler4 { private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>(); private final ReentrantLock reentrantLock = new ReentrantLock(); private Session session; @OnOpen public void handleOpen(Session session, @PathParam("token") String token) { this.session = session; // if (StringUtils.isEmpty(token)) { // sendInfo("[websocket ERROR] 客户端Token错误,连接失败"); // } webSocketMap.put(session.getId(), this); log.info("[websocket]客户端创建连接,session ID = {} ", session.getId()); log.info("webSocketMap内容:" + webSocketMap); } @OnClose public void handleClose(Session session) { if (webSocketMap.containsKey(session.getId())) { webSocketMap.remove(session.getId()); } log.info("[websocket]客户端断开websocket连接,session ID = {} ", session.getId()); } @OnError public void handleError(Session session, Throwable throwable) { log.info("[websocket]出现错误,session ID = {} ", session.getId()); log.info("[websocket]出现错误,throwable = {} ", throwable); } // 发送数据到客户端 public static void sendInfo(String message) { for (String item : webSocketMap.keySet()) { webSocketMap.get(item).sendMessage(message); } } public void sendMessage(String message) { try { //加锁 reentrantLock.lock(); if (this.session != null && this.session.isOpen()) { this.session.getBasicRemote().sendText(message); } } catch (IOException e) { e.printStackTrace(); } finally { //解锁 reentrantLock.unlock(); } } }