WebSocketCilent

WebSocketCilent

package org.dlzx.wygk.response.handle.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.core.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class HwMeetingWebSocketClient extends WebSocketClient {

	//依赖注入service
    private static XXXService service;

    @Autowired
    public void setApplicationContext(IXyczHwMeetingMemberService memberService) {
        HwMeetingWebSocketClient.memberService = memberService;
    }

	//定时发送心跳
    private final ScheduledExecutorService heartbeatExecutor;
    private static final int HEARTBEAT_INTERVAL = 60; // seconds

    public HwMeetingWebSocketClient(@Value("") String url) throws URISyntaxException {
        super(new URI(url));
        this.heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
        startHeartbeat();
    }

    private void startHeartbeat() {
        heartbeatExecutor.scheduleAtFixedRate(() -> {
            if (isOpen()) {
                sendHeartbeat();
            }
        }, HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
    }

    private void sendHeartbeat() {
        Map<String, String> map = new HashMap<>();
        map.put("action", "HeartBeat");
        map.put("sequence", String.valueOf(System.currentTimeMillis()));
        send(map.toString());
        log.info("sendHeartbeat");
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {

    }

    @Override
    public void onMessage(String s) {
    	//处理收到的推送消息
        log.info("s:{}", s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {

    }

    @Override
    public void onError(Exception e) {

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值