zoukankan      html  css  js  c++  java
  • 使用spring boot +WebSocket的那些坑

    springboot和websocket通讯时的坑有一个:下面这个东西要有

    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    
    /**
     * Created with IntelliJ IDEA.
     *
     * @author: xincheng.zhao
     * @date: 2018/9/4
     * @description:
     */
    @Configuration
    public class WebSocketConfig {
    
        @Bean
        public ServerEndpointExporter  serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }
    
    
    

    spring里面还有创建下面的:

    @ServerEndpoint(value = "/websocket")
    @Component
    public class WSController {
        //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
        //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
        private static CopyOnWriteArraySet<WSController> webSocketSet = new CopyOnWriteArraySet<WSController>();
    
        //与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
    
        /**
         * 连接建立成功调用的方法*/
        @OnOpen
        public void onOpen(Session session) {
            this.session = session;
            webSocketSet.add(this);     //加入set中
            System.out.println("有新连接加入!当前在线人数为");
        }
    //
    //    	//连接打开时执行
    //    	@OnOpen
    //    	public void onOpen(@PathParam("user") String user, Session session) {
    //    		currentUser = user;
    //    		System.out.println("Connected ... " + session.getId());
    //    	}
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
            webSocketSet.remove(this);  //从set中删除
            System.out.println("websocket close");
        }
        /*
         *收到客户端消息
         */
        @OnMessage
        public  void onMessage(String message ,Session session){
            System.out.println("收到客户端的消息:"+message);
        }
    
    }
    

    js里面实现:

      layim.on("sendMessage",function (res) {
            ws.send(JSON.stringify({
                type:"chatMessage",
                data:res
            }))
            layer.msg("发送消息成功")
        })
    

    其他要配置好

    小白技术社
  • 相关阅读:
    Selenium等待:sleep、隐式、显式和Fluent
    开源礼节
    IntelliJ中基于文本的HTTP客户端
    Selenium4 IDE特性:弹性测试、循环和逻辑判断
    CF 1400G.Mercenaries 题解【SOSDP 组合数学】
    Educational Codeforces Round 33
    Educational Codeforces Round 32
    Educational Codeforces Round 31
    Educational Codeforces Round 30
    Educational Codeforces Round 29
  • 原文地址:https://www.cnblogs.com/xbjss/p/13326705.html
Copyright © 2011-2022 走看看