| | |
| | | * WebSocket服务类 |
| | | * @author WWW |
| | | */ |
| | | @ServerEndpoint(value = "/ws") |
| | | @ServerEndpoint(value = "/ws/select") |
| | | @Component |
| | | public class WebSocketService { |
| | | @PostConstruct |
| | |
| | | System.out.println("websocket 加载"); |
| | | } |
| | | |
| | | private static Logger log = LoggerFactory.getLogger(WebSocketService.class); |
| | | private final static Logger log = LoggerFactory.getLogger(WebSocketService.class); |
| | | |
| | | private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0); |
| | | |
| | | /** |
| | | * 用来存放每个客户端对应的Session对象(线程安全Set) |
| | | */ |
| | | private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>(); |
| | | private final static CopyOnWriteArraySet<Session> SESSION_SET = new CopyOnWriteArraySet<Session>(); |
| | | |
| | | /** |
| | | * 连接建立成功调用的方法 |
| | | */ |
| | | @OnOpen |
| | | public void onOpen(Session session) { |
| | | SessionSet.add(session); |
| | | SESSION_SET.add(session); |
| | | |
| | | int cnt = ONLINE_COUNT.incrementAndGet(); |
| | | log.info("有连接加入,当前连接数为:{}", cnt); |
| | |
| | | */ |
| | | @OnClose |
| | | public void onClose(Session session) { |
| | | SessionSet.remove(session); |
| | | SESSION_SET.remove(session); |
| | | |
| | | int cnt = ONLINE_COUNT.decrementAndGet(); |
| | | log.info("有连接关闭,当前连接数为:{}", cnt); |
| | |
| | | @OnError |
| | | public void onError(Session session, Throwable error) { |
| | | log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId()); |
| | | error.printStackTrace(); |
| | | } |
| | | |
| | | /** |
| | |
| | | public static void sendMessage(Session session, String message) { |
| | | try { |
| | | session.getBasicRemote().sendText(String.format("%s", message)); |
| | | } catch (IOException e) { |
| | | log.error("发送消息出错:{}", e.getMessage()); |
| | | e.printStackTrace(); |
| | | } catch (Exception ex) { |
| | | log.error("发送消息出错:{}", ex.getMessage()); |
| | | } |
| | | } |
| | | |
| | |
| | | * @throws IOException |
| | | */ |
| | | public static void broadCastInfo(String message) throws IOException { |
| | | for (Session session : SessionSet) { |
| | | for (Session session : SESSION_SET) { |
| | | if (session.isOpen()) { |
| | | sendMessage(session, message); |
| | | } |
| | |
| | | */ |
| | | public static void sendMessage(String message, String sessionId) throws IOException { |
| | | Session session = null; |
| | | for (Session s : SessionSet) { |
| | | for (Session s : SESSION_SET) { |
| | | if (s.getId().equals(sessionId)) { |
| | | session = s; |
| | | break; |
| | |
| | | if (session != null) { |
| | | sendMessage(session, message); |
| | | } else { |
| | | log.warn("没有找到你指定ID的会话:{}", sessionId); |
| | | log.info("没有找到你指定ID的会话:{}", sessionId); |
| | | } |
| | | } |
| | | } |