package com.iailab.module.websocket.server; import com.iailab.module.websocket.config.ServerEncoder; 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.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * @author lirm * @Description * @createTime 2023.11.23 */ @Slf4j @Component @ServerEndpoint(encoders={ServerEncoder.class},value = "/socket/{username}") public class WebSocketServer { /** * 储存当前对象 */ private static Map sessionMap = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("username") String username) { sessionMap.put(username, session); } @OnClose public void onClose(@PathParam("username") String username) { if (sessionMap.containsKey(username)) { sessionMap.remove(username); } } @OnMessage public void onMessage(String message) { broadcastAllUser(message); } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } public void broadcastUsers(List users, Object message) { try { Set strings = sessionMap.keySet(); for (String name : users) { if (strings.contains(name)) { sessionMap.get(name).getBasicRemote().sendObject(message); } } } catch (Exception ex) { log.error("广播消息出现异常"); ex.printStackTrace(); } } public void broadcastAllUser(String message) { try { Set strings = sessionMap.keySet(); for (String name : strings) { sessionMap.get(name).getBasicRemote().sendText(message); } } catch (Exception ex) { log.error("广播消息出现异常"); ex.printStackTrace(); } } }