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) {
}
}