WebSocket实现实时推送数据到前端

@Component
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{

    @Resource
    goodsWebSocketHandler handler;
 
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
     
        //配置对指定的url进行拦截
        registry.addHandler(handler, "/mi/*").addInterceptors(new HandShakeInterceptor());
 
        //允许客户端使用SokcetJs
        registry.addHandler(handler, "/mi/*/*").addInterceptors(new HandShakeInterceptor()).withSockJS();
    }

}

 

 

/**
 * 每次建立连接都会进行握手,这个拦截器是用于处理握手前后的预处理工作

 *
 */
public class HandShakeInterceptor implements HandshakeInterceptor {

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
        System.out.println("将要进入WebSocket预处理过程");
        return true;
    }
 
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
     System.out.println("WebSocket预处理中....");
     System.out.println("webSocket预处理完毕");
    }

}

 

 

 

 

 

@Component
public class goodsWebSocketHandler implements WebSocketHandler {
     private volatile static List users = new ArrayList<>();
     
     private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     @Value("${push.time}")
     private Long pushTime;

    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
          users.add(session);
     /*new Thread(new Runnable() {
               @Override
               public void run() {
                    while(true) {
                         for(WebSocketSession user:users) {//向每个在线的客户端推送消息,4秒推送一次
                              try {
                                   user.sendMessage(new TextMessage("服务器推送消息:" + sdf.format(new Date())));
                              } catch (IOException e) {
                                   e.printStackTrace();
                              }
                         }
                         try {//服务器每5秒向每个在线的客户端推送消息
                              Thread.currentThread().sleep(30000);
                         } catch (InterruptedException e) {
                              e.printStackTrace();
                         }
                    }
               }
          }).start();*/
    }
 
    public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
          String gainMessage = message.getPayload().toString();
//        System.err.println("接收到客户端:" + session.getId() + "发送的消息:" + gainMessage);
          Map params = null;
          if (.isNotEmpty(gainMessage)) {
               params = JSON.parseObject(gainMessage);
          }
          if(.isNotEmpty(params.get("HeartBeat")) || MonkeyUtils.isEmpty(gainMessage)){
               Map map = new HashedMap();
               map.put("HeartBeat",true);
               map.put("HeartBeatDate",sdf.format(new Date()));
               session.sendMessage(new TextMessage(JSON.toJSONString(map)));
          }else{
               for (WebSocketSession mySession : users) {
                    if (mySession.equals(session)) {
                         synchronized (this) {
                              if (session.isOpen()) {
                                   Map finalParams = params;
                                   new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                             while (true) {
                                                  try {
                                                       if(session.isOpen()){
                                                             //业务操作   查询数据
                                                            List collages = new HashMap<>();
                                                            session.sendMessage(new TextMessage(JSON.toJSONString(collages)));
                                                       }else{
                                                            break;
                                                       }
                                                  } catch (IOException e) {
                                                       e.printStackTrace();
                                                  }
                                                  try {
                                                       //5秒刷新一次
                                                       Thread.sleep(collagePushTime);
                                                  } catch (InterruptedException e) {
                                                       e.printStackTrace();
                                                  }
                                             }
                                        }
                                   }).start();
                              }
                         }
                    }
               }
          }
    }
 
    public void handleTransportError(WebSocketSession session,Throwable exception) throws Exception {
        users.remove(session);
    }
 
    public void afterConnectionClosed(WebSocketSession session,CloseStatus closeStatus) throws Exception {
        users.remove(session);
        session.close();
    }
 
    public boolean supportsPartialMessages() {
        return false;
    }

    private List getData(WebSocketSession session,Map param){

     return null;
     }

}







            javax.websocket
            javax.websocket-api
            1.0
            provided
        
        
            org.springframework
            spring-websocket
            4.0.1.RELEASE
        
        
            org.springframework
            spring-messaging
            4.0.1.RELEASE
        

你可能感兴趣的:(websocket)