1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| @ServerEndpoint("/websocket/{sid}") @Component public class WebSocketServer {
private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final AtomicInteger onlineCount = new AtomicInteger(0); private static final ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private Session session; private String sid;
@OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { this.session = session; this.sid = sid; if (webSocketMap.containsKey(sid)) { webSocketMap.remove(sid); webSocketMap.put(sid, this); } else { webSocketMap.put(sid, this); onlineCount.getAndIncrement(); } log.info("开启连接: {}, 当前连接数: {}", sid, onlineCount); sendMessage("连接成功"); }
@OnClose public void onClose() { if (webSocketMap.containsKey(sid)) { webSocketMap.remove(sid); onlineCount.getAndDecrement(); } log.info("关闭连接: {}, 当前连接数: {}", sid, onlineCount); }
@OnMessage public void onMessage(Session session, String message) { log.info("接收客户端消息: {}, {}", sid, message); if ("START".equals(message)) { new FileMonitorTask(session, "E:\\1.txt", 1000L).start(); } }
@OnError public void onError(Session session, Throwable error) { log.error("连接错误: {}", sid, error); }
public void sendMessage(String message) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("发送消息失败: {}, {}", sid, message); } } }
|