• websocket简单使用


    @ServerEndpoint(value = "/datatrans/socketServer/{datatransSocket}")
    @Component
    public class SocketServer {
    
        private Session session;
    
        private static Map<String, Session> sessionPool = new ConcurrentHashMap<>();
        private static Map<String, String> sessionIds = new ConcurrentHashMap<>();
    
        public SocketServer() {
        }
    
        @OnOpen
        public void open(Session session, @PathParam(value = "datatransSocket") String datatransSocket) {
            this.session = session;
            sessionPool.put(datatransSocket, session);
            sessionIds.put(session.getId(), datatransSocket);
            System.out.println("websocket-成功");
        }
    
        @OnMessage
        public void onMessage(String message) {
            System.out.println("当前发送人sessionid为" + session.getId() + "发送内容为" + message);
        }
    
        @OnClose
        public void onClose() {
            sessionPool.remove(sessionIds.get(session.getId()));
            sessionIds.remove(session.getId());
        }
    
        @OnError
        public void onError(Session session, Throwable error) {
            error.printStackTrace();
        }
    
        public void sendMessage( String message) {
            Session session = sessionPool.get("datatransSocket");
            if (session == null) {
                return;
            }
            synchronized (session) {
                if (session != null) {
                    try {
                        session.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public static int getOnlineNum() {
            return sessionPool.size();
        }
    
        public String getOnlineTUsers() {
            StringBuilder TUsers = new StringBuilder();
            for (String key : sessionIds.keySet()) {
                TUsers.append(sessionIds.get(key)).append("---------");
            }
            return TUsers.toString();
        }
    
        public void sendAll(String msg) {
            //for (String key : sessionIds.keySet()) {
            //    sendMessage(sessionIds.get(key), msg);
            //}
            sendMessage(msg);
        }
    
        public void sendMany(String msg, String[] persons) {
            for (String TUserid : persons) {
                sendMessage(msg);
            }
        }
    }
    SocketServer
  • 相关阅读:
    PDO应用
    分页查询
    PHP去除数组中重复数据的两个例子
    数据库访问(现用基本格式)
    克隆、加载类
    抽象类和接口
    静态
    PHP基础
    数据库的常用函数
    数据库的高级查询
  • 原文地址:https://www.cnblogs.com/xiangpeng/p/12803124.html
Copyright © 2020-2023  润新知