WebSocket通信协议实现实时消息推送

Websocket与前端建立通道连接时时推送数据 下面看代码

pom引入jar包



   org.springframework.boot
   spring-boot-starter-websocket

 

服务端配置

@Configuration
public class WebSocketConfig {
    /**
     *     注入ServerEndpointExporter,
     *     这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    
}

服务端逻辑代码

 

/**
 * @Author 
 * @Date 
 * @Description: 此注解相当于设置访问URL
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}") //此注解相当于设置访问URL
public class WebSocket {
    
    private Session session;
    
    private static CopyOnWriteArraySet webSockets =new CopyOnWriteArraySet<>();
    private static Map sessionPool = new HashMap();
    
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        try {
         this.session = session;
         webSockets.add(this);
         sessionPool.put(userId, session);
         log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
      } catch (Exception e) {
      }
    }
    
    @OnClose
    public void onClose() {
        try {
         webSockets.remove(this);
         log.info("【websocket消息】连接断开,总数为:"+webSockets.size());
      } catch (Exception e) {
      }
    }
    
    @OnMessage
    public void onMessage(String message) {
        //todo 现在有个定时任务刷,应该去掉
       log.debug("【websocket消息】收到客户端消息:"+message);
       JSONObject obj = new JSONObject();
       obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);//业务类型
       obj.put(WebsocketConst.MSG_TXT, "心跳响应");//消息内容
       session.getAsyncRemote().sendText(obj.toJSONString());
    }
    
    // 此为广播消息
    public void sendAllMessage(String message) {
       log.info("【websocket消息】广播消息:"+message);
        for(WebSocket webSocket : webSockets) {
            try {
               if(webSocket.session.isOpen()) {
                  webSocket.session.getAsyncRemote().sendText(message);
               }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null&&session.isOpen()) {
            try {
               log.info("【websocket消息】 单点消息:"+message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
       for(String userId:userIds) {
          Session session = sessionPool.get(userId);
            if (session != null&&session.isOpen()) {
                try {
                   log.info("【websocket消息】 单点消息:"+message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
       }
        
    }
    
}

测试代码

 

@RestController
@RequestMapping("webSocketApi")
public class TestController {
   
    @Autowired
    private WebSocket webSocket;
 
    @PostMapping("/sendAll")
    public Result sendAll(@RequestBody JSONObject jsonObject) {
       Result result = new Result();
       String message = jsonObject.getString("message");
       JSONObject obj = new JSONObject();
       obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
       obj.put(WebsocketConst.MSG_ID, "M0001");
       obj.put(WebsocketConst.MSG_TXT, message);
       webSocket.sendAllMessage(obj.toJSONString());
        result.setResult("群发!");
        return result;
    }

    @PostMapping("/sendUser")
    public Result sendUser(@RequestBody JSONObject jsonObject) {
       Result result = new Result();
       String userId = jsonObject.getString("userId");
       String message = jsonObject.getString("message");
       JSONObject obj = new JSONObject();
       obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
       obj.put(WebsocketConst.MSG_USER_ID, userId);
       obj.put(WebsocketConst.MSG_ID, "M0001");
       obj.put(WebsocketConst.MSG_TXT, message);
        webSocket.sendOneMessage(userId, obj.toJSONString());
        result.setResult("单发");
        return result;
    }
    
}

 

你可能感兴趣的:(websocket,java)