For the complete documentation index, see llms.txt. This page is also available as Markdown.

WebSocket Code Example

The examples send application heartbeat 10010 every 30 seconds and resubscribe after reconnecting. They strip a Subscribe fail: prefix before parsing JSON and display plain-text messages. 507 means a missing parameter, not failed authentication. For extra mark-price fields, use an actual crypto contract such as BTCUSDT.P and set withMarkPrice: true inside the trade subscription data. The default examples subscribe to spot.

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@ClientEndpoint
@Slf4j
@Component
public class WebsocketExample {

    private static final Set<Integer> ACK_CODES = Set.of(10001, 10004, 10007, 11010);

    private volatile Session session;
    private ScheduledExecutorService scheduler;
    private volatile ScheduledFuture<?> heartbeatFuture;
    private volatile boolean authFailed;

    private String wsUrl() {
        String key = System.getenv().getOrDefault("INFOWAY_API_KEY", "yourApikey");
        return "wss://data.infoway.io/ws?business=crypto&apikey="
                + URLEncoder.encode(key, StandardCharsets.UTF_8);
    }

    @PostConstruct
    public void connectAll() {
        // 订阅与心跳不要挤在同一个单线程上
        scheduler = Executors.newScheduledThreadPool(2);
        connect();
        scheduler.scheduleAtFixedRate(() -> {
            if (authFailed) {
                return;
            }
            Session current = session;
            if (current == null || !current.isOpen()) {
                connect();
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    private void connect() {
        try {
            cancelHeartbeat();
            if (session != null && session.isOpen()) {
                session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "reconnect"));
            }
            session = ContainerProvider.getWebSocketContainer().connectToServer(this, URI.create(wsUrl()));
        } catch (Exception e) {
            session = null;
            String msg = String.valueOf(e.getMessage());
            if (msg.contains("401") || msg.contains("407")) {
                authFailed = true;
                log.error("鉴权失败,停止重连: {}", msg);
                return;
            }
            log.error("WebSocket 连接失败: {}", msg);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        authFailed = false;
        startHeartbeat(session);
        scheduler.execute(() -> {
            try {
                sendTradeSubscribe(session);
                sendDepthSubscribe(session);
                sendKlineSubscribe(session);
            } catch (IOException e) {
                log.error("发送订阅失败: {}", e.getMessage());
            }
        });
    }

    private void sendTradeSubscribe(Session session) throws IOException {
        JSONObject body = new JSONObject();
        body.put("code", 10000);
        body.put("trace", UUID.randomUUID().toString());
        JSONObject data = new JSONObject();
        data.put("codes", "BTCUSDT");
        body.put("data", data);
        session.getBasicRemote().sendText(body.toJSONString());
    }

    private void sendDepthSubscribe(Session session) throws IOException {
        JSONObject body = new JSONObject();
        body.put("code", 10003);
        body.put("trace", UUID.randomUUID().toString());
        JSONObject data = new JSONObject();
        data.put("codes", "BTCUSDT");
        body.put("data", data);
        session.getBasicRemote().sendText(body.toJSONString());
    }

    private void sendKlineSubscribe(Session session) throws IOException {
        JSONObject body = new JSONObject();
        body.put("code", 10006);
        body.put("trace", UUID.randomUUID().toString());
        JSONObject item = new JSONObject();
        item.put("type", 1);
        item.put("codes", "BTCUSDT");
        JSONObject data = new JSONObject();
        data.put("arr", new JSONArray().fluentAdd(item));
        body.put("data", data);
        session.getBasicRemote().sendText(body.toJSONString());
    }

    private void startHeartbeat(Session active) {
        cancelHeartbeat();
        heartbeatFuture = scheduler.scheduleAtFixedRate(() -> {
            try {
                if (active.isOpen() && active == this.session) {
                    JSONObject ping = new JSONObject();
                    ping.put("code", 10010);
                    ping.put("trace", UUID.randomUUID().toString());
                    active.getBasicRemote().sendText(ping.toJSONString());
                }
            } catch (IOException e) {
                log.error("发送心跳失败: {}", e.getMessage());
            }
        }, 30, 30, TimeUnit.SECONDS);
    }

    private void cancelHeartbeat() {
        ScheduledFuture<?> future = heartbeatFuture;
        if (future != null) {
            future.cancel(false);
            heartbeatFuture = null;
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        String payload = message.startsWith("Subscribe fail:")
                ? message.substring("Subscribe fail:".length()).stripLeading() : message;
        JSONObject msg;
        try {
            msg = JSONObject.parseObject(payload);
        } catch (RuntimeException e) {
            log.warn("WebSocket text: {}", payload);
            return;
        }
        if (msg == null || !msg.containsKey("code")) {
            log.warn("WebSocket text: {}", payload);
            return;
        }
        Integer code = msg.getInteger("code");
        if (code == null) {
            return;
        }
        Object data = msg.get("data");
        switch (code) {
            case 200 -> log.info("连接成功: {}", msg.getString("msg"));
            case 10002 -> log.info("成交推送: {}", data);
            case 10005 -> log.info("盘口推送: {}", data);
            case 10008 -> log.info("K线推送: {}", data);
            case 10011 -> log.debug("心跳确认: {}", msg.getString("trace"));
            default -> {
                if (ACK_CODES.contains(code)) {
                    log.info("订阅确认 code={} trace={} msg={}", code, msg.getString("trace"), msg.getString("msg"));
                } else if (code >= 500 && code < 10000) {
                    log.error("业务错误 code={} msg={}", code, msg.getString("msg"));
                    if (code >= 508 && code <= 511) {
                        authFailed = true;
                    }
                } else {
                    log.warn("未处理协议号 {}: {}", code, message);
                }
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        cancelHeartbeat();
        this.session = null;
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket 错误", error);
        cancelHeartbeat();
        this.session = null;
    }

    @PreDestroy
    public void destroy() {
        cancelHeartbeat();
        if (session != null && session.isOpen()) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "shutdown"));
            } catch (IOException ignored) {
            }
        }
        if (scheduler != null) {
            scheduler.shutdownNow();
        }
    }
}

Last updated