zoukankan      html  css  js  c++  java
  • SpringBoot+WebSocket

    SpringBoot+WebSocket 只需三个步骤

    1. 导入依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
    1. 添加配置使得ServerEndpoint生效
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    
    1. 写Websocket程序
    @ServerEndpoint(value = "/websocket2")
    @Component
    public class MyWebSocket
    {
        /**
         * 在线人数
         */
        public static int onlineNumber = 0;
    
        /**
         * 所有的对象
         */
        public static List<MyWebSocket> webSockets = new CopyOnWriteArrayList<MyWebSocket>();
    
        /**
         * 会话
         */
        private Session session;
    
        /**
         * 建立连接
         *
         * @param session
         */
        @OnOpen
        public void onOpen(Session session)
        {
            onlineNumber++;
            webSockets.add(this);
    
            this.session = session;
    
            System.out.println("有新连接加入! 当前在线人数" + onlineNumber);
        }
    
        /**
         * 连接关闭
         */
        @OnClose
        public void onClose()
        {
            onlineNumber--;
            webSockets.remove(this);
            System.out.println("有连接关闭! 当前在线人数" + onlineNumber);
        }
    
        /**
         * 收到客户端的消息
         *
         * @param message 消息
         * @param session 会话
         */
        @OnMessage
        public void onMessage(String message, Session session)
        {
            System.out.println("来自客户端消息:" + message);
    
            sendMessage("欢迎连接");
        }
    
        /**
         * 发送消息
         *
         * @param message 消息
         */
        public void sendMessage(String message)
        {
            try
            {
                session.getBasicRemote().sendText(message);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
  • 相关阅读:
    XSS
    web安全之sql注入
    12、API
    7、源与值(Source/Values)
    3、高级方法(Advanced Recipes)
    树莓派实现SIM868 ppp拨号上网
    【转】在树莓派上实现人脸识别
    树莓派raspbian安装matchbox-keyboard虚拟键盘
    python+树莓派实现IoT(物联网)数据上传到服务器
    python安装MySQLclient
  • 原文地址:https://www.cnblogs.com/bihanghang/p/10763199.html
Copyright © 2011-2022 走看看