原生WebSocket使用案例

原生WebSocket使用案例

最近做项目,需求是使用WebSocket将服务器接收到事件预警需要直接推送到前端,设置定时任务5分钟推送一次。具体代码如下:

WebSocket配置类

@Configuration
public class WebSocketConfigure {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

WebSocket服务类

@Component
@ServerEndpoint(value = "/webSocket")
public class WebSocketServer {
    private static final AriesJcLogger logger = AriesJcLoggerFactory.getLogger(WebSocketServer.class);
    //记录当前在线连接数
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<WebSocketServer, String> sessionWithIdMap = new ConcurrentHashMap<>();
    private Session session;


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        logger.info("====加入新连接session:{}!当前在线人数为:{}", this.session.getId(), getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            logger.error("websocket IO异常", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        //移除sessionWtihBuildingMap中对应的对象
        sessionWithIdMap.remove(this);
        subOnlineCount();           //在线数减1
        logger.info("====关闭连接session:{}!当前在线人数为:{}", this.session.getId(), getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        logger.debug("====来自客户端的消息session:{}---message:{}", session.getId(), message);
        this.session = session;
        //保存session和对应的id
        sessionWithIdMap.put(this, message);
        sendMessage(JSON.toJSONString("socketResult=>" + message));
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("websocket 发生错误", error.getMessage(), error);
        //error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        logger.debug("发送至客户端的消息:" + message);
        this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 获取所有websocket
     */
    public CopyOnWriteArraySet<WebSocketServer> getWebSockets() {
        return webSocketSet;
    }

    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) throws IOException {
        if (getOnlineCount() > 0) {
            for (WebSocketServer item : webSocketSet) {
                try {
                    synchronized (item) {
                        item.sendMessage(message);

                    }

                } catch (IOException e) {
                    logger.error("sendInfo error:{}", e);
                }
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

具体业务实现

@Component
public class TimeTask {

    private static final AriesJcLogger logger = AriesJcLoggerFactory.getLogger(TimeTask.class);
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private AlarmEventService alarmEventService;

//    @Value("${interval.time}")
//    private Integer intervalTime;
    @Scheduled(cron="${interval.time}")
    public void test(){
        logger.info("time task starting...");
        try{
            //获取后端推送的事件列表
            BaseResult<List<Result4AlarmEventListDto>> alarmEventList = alarmEventService.getAlarmEventList();
          //  List<Result4AlarmEventListDto> list = alarmEventList.getData();
            //list集合转换为String
            if (alarmEventList!=null){
                String alarmList = JSONObject.toJSONString(alarmEventList);
                webSocketServer.sendInfo(alarmList);
                logger.info("send message ending...");
            }

        }catch (Exception e){
            logger.errorWithErrorCode(ErrorCode.WebSocket.WEBSOCKET_PUSH_EVENT_WEB, "Alarm event init data occurred exception.", e);
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值