新版仿ok交易所-后端
zyy
2025-10-25 f4374f91ad562a357702e2ab4faeb1428d1172b1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package com.yami.trading.huobi.data.websocket.service.huobi.connection;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yami.trading.huobi.data.websocket.constant.Options;
import com.yami.trading.huobi.data.websocket.constant.enums.ConnectionStateEnum;
import com.yami.trading.huobi.data.websocket.service.huobi.parser.HuobiModelParser;
import com.yami.trading.huobi.data.websocket.utils.*;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
 
public class HuobiWebSocketConnection extends WebSocketListener implements WebSocketConnection {
 
    private static Logger log = LoggerFactory.getLogger(HuobiWebSocketConnection.class);
 
    public static final String HUOBI_TRADING_WEBSOCKET_PATH = "/ws/v1";
    public static final String HUOBI_TRADING_WEBSOCKET_V2_PATH = "/ws/v2";
    public static final String HUOBI_MARKET_WEBSOCKET_PATH = "/ws";
 
    public static final String AUTH_VERSION_V1 = "v1";
 
    private long lastReceivedTime;
 
    private WebSocket webSocket;
 
    private Request okhttpRequest;
 
    private ConnectionStateEnum state;
 
    private Long id;
 
    private List<String> commandList;
 
    private HuobiModelParser parser;
 
    private ResponseCallback callback;
 
    private boolean autoClose;
 
    private boolean authNeed;
 
    private Options options;
 
    private long delayInSecond;
 
    private String host;
 
    private String authVersion = AUTH_VERSION_V1;
 
    private HuobiWebSocketConnection() {
    }
 
    public static HuobiWebSocketConnection createAssetConnection(Options options, List<String> commandList,
            HuobiModelParser parser, ResponseCallback callback, Boolean autoClose) {
 
        return createConnection(options, commandList, parser, callback, autoClose, true);
    }
 
    public static HuobiWebSocketConnection createMarketConnection(Options options, List<String> commandList,
            HuobiModelParser parser, ResponseCallback callback, boolean autoClose) {
        return createConnection(options, commandList, parser, callback, autoClose, false);
    }
 
    public static HuobiWebSocketConnection createConnection(Options options, List<String> commandList,
            HuobiModelParser parser, ResponseCallback callback, Boolean autoClose, boolean authNeed) {
        return createConnection(options, commandList, parser, callback, autoClose, authNeed, AUTH_VERSION_V1);
    }
 
    public static HuobiWebSocketConnection createConnection(Options options, List<String> commandList,
            HuobiModelParser parser, ResponseCallback callback, Boolean autoClose, boolean authNeed,
            String authVersion) {
 
        HuobiWebSocketConnection connection = new HuobiWebSocketConnection();
        connection.setOptions(options);
        connection.setCommandList(commandList);
        connection.setParser(parser);
        connection.setCallback(callback);
        connection.setAuthNeed(authNeed);
        connection.setAutoClose(autoClose);
        connection.setId(IdGenerator.getNextId());
        connection.setAuthVersion(authVersion);
 
        // 创建websocket请求
        String url = options.getWebSocketHost() + HUOBI_MARKET_WEBSOCKET_PATH;
        Request request = new Request.Builder().url(url).build();
        connection.setOkhttpRequest(request);
 
        try {
            connection.setHost(new URL(options.getRestHost()).getHost());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
 
        // 开启链接
        connection.connect();
        return connection;
    }
 
    void connect() {
        if (state == ConnectionStateEnum.CONNECTED || webSocket != null) {
            log.info("[Connection][" + this.getId() + "] Already connected");
            return;
        }
        log.info("[Connection][" + this.getId() + "] Connecting...");
        webSocket = ConnectionFactory.createWebSocket(okhttpRequest, this);
    }
 
    public void reConnect(int delayInSecond) {
        log.warn("[Sub][" + this.getId() + "] Reconnecting after " + delayInSecond + " seconds later");
        if (webSocket != null) {
            // 发送重连关闭帧(1001:端点离开)
            webSocket.close(1001, "Reconnecting");
            webSocket = null;
        }
        this.delayInSecond = delayInSecond;
        state = ConnectionStateEnum.DELAY_CONNECT;
    }
 
    public void reConnect() {
        if (delayInSecond != 0) {
            delayInSecond--;
        } else {
            connect();
        }
    }
 
    public long getLastReceivedTime() {
        return this.lastReceivedTime;
    }
 
    void send(List<String> commandList) {
        if (commandList == null || commandList.size() <= 0) {
            return;
        }
        commandList.forEach(command -> {
            send(command);
        });
    }
 
    public void send(String str) {
        boolean result = false;
        log.info("[Connection Send]{}", str);
        if (webSocket != null) {
            result = webSocket.send(str);
        }
        if (!result) {
            log.error("[Connection Send][" + this.getId() + "] Failed to send message");
            closeOnError();
        }
    }
 
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        super.onMessage(webSocket, text);
        lastReceivedTime = System.currentTimeMillis();
 
        log.debug("[On Message Text]:{}", text);
        try {
            JSONObject json = JSON.parseObject(text);
 
            if (json.containsKey("action")) {
                String action = json.getString("action");
                if ("ping".equals(action)) {
                    processPingOnV2TradingLine(json, webSocket);
                } else if ("push".equals(action)) {
                    onReceive(json);
                }
                if ("req".equals(action)) {
                    String ch = json.getString("ch");
                    if ("auth".equals(ch)) {
                        send(commandList);
                    }
 
                }
 
            }
 
        } catch (Exception e) {
            log.error("[On Message][{}]: catch exception:", this.getId(), e);
            closeOnError();
        }
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        super.onMessage(webSocket, bytes);
        try {
 
            lastReceivedTime = System.currentTimeMillis();
 
            String data;
            try {
                data = new String(InternalUtils.decode(bytes.toByteArray()));
            } catch (IOException e) {
                log.error("[Connection On Message][" + this.getId() + "] Receive message error: " + e.getMessage());
                closeOnError();
                return;
            }
            log.debug("[Connection On Message][{}] {}", this.getId(), data);
            JSONObject jsonObject = JSON.parseObject(data);
 
            if (jsonObject.containsKey("status") && !"ok".equals(jsonObject.getString("status"))) {
                String errorCode = jsonObject.getString("err-code");
                String errorMsg = jsonObject.getString("err-msg");
                onError(errorCode + ": " + errorMsg, null);
                log.error("[Connection On Message][" + this.getId() + "] Got error from server: " + errorCode + "; "
                        + errorMsg);
                close();
            } else if (jsonObject.containsKey("op")) {
                String op = jsonObject.getString("op");
                if (op.equals("notify")) {
                    onReceive(jsonObject);
                } else if (op.equals("ping")) {
                    processPingOnTradingLine(jsonObject, webSocket);
                } else if (op.equals("auth")) {
                    send(commandList);
                } else if (op.equals("req")) {
                    onReceiveAndClose(jsonObject);
                }
            } else if (jsonObject.containsKey("ch") || jsonObject.containsKey("rep")) {
                onReceiveAndClose(jsonObject);
            } else if (jsonObject.containsKey("ping")) {
                processPingOnMarketLine(jsonObject, webSocket);
            } else if (jsonObject.containsKey("subbed")) {
            }
        } catch (Exception e) {
            log.error("[Connection On Message][" + this.getId() + "] Unexpected error: " + e.getMessage());
            closeOnError();
        }
    }
 
    private void onError(String errorMessage, Throwable e) {
        log.error("[Connection error][" + this.getId() + "] " + errorMessage);
        closeOnError();
    }
 
    private void onReceiveAndClose(JSONObject jsonObject) {
        onReceive(jsonObject);
        if (autoClose) {
            close();
        }
    }
 
    @SuppressWarnings("unchecked")
    private void onReceive(JSONObject jsonObject) {
        Object obj = null;
        try {
            obj = parser.parse(jsonObject);
        } catch (Exception e) {
            onError("Process error: " + e.getMessage() + " You should capture the exception in your error handler", e);
            return;
        }
 
        callback.onResponse(obj);
    }
 
    private void processPingOnTradingLine(JSONObject jsonObject, WebSocket webSocket) {
        long ts = jsonObject.getLong("ts");
        webSocket.send(String.format("{\"op\":\"pong\",\"ts\":%d}", ts));
    }
 
    private void processPingOnMarketLine(JSONObject jsonObject, WebSocket webSocket) {
        long ts = jsonObject.getLong("ping");
        webSocket.send(String.format("{\"pong\":%d}", ts));
    }
 
    private void processPingOnV2TradingLine(JSONObject jsonWrapper, WebSocket webSocket) {
        long ts = jsonWrapper.getJSONObject("data").getLong("ts");
        String pong = String.format("{\"action\": \"pong\",\"params\": {\"ts\": %d}}", ts);
        webSocket.send(pong);
    }
 
    public ConnectionStateEnum getState() {
        return state;
    }
 
    @Override
    public Long getConnectionId() {
        return this.getId();
    }
 
    public void close() {
        log.error("[Connection close][" + this.getId() + "] Closing normally");
        if (webSocket != null) {
            // 发送正常关闭帧(1000:正常关闭)
            webSocket.close(1000, "Normal close");
            webSocket = null; // 置空,避免重复操作
        }
        WebSocketWatchDog.onClosedNormally(this);
    }
 
    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);
        log.info("[Connection closed][" + this.getId() + "] Code: " + code + ", Reason: " + reason);
        this.webSocket = null; // 确保旧连接引用被清除
        state = ConnectionStateEnum.IDLE;
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        this.webSocket = webSocket;
        log.info("[Connection][" + this.getId() + "] Connected to server");
        if (options.isWebSocketAutoConnect()) {
            WebSocketWatchDog.onConnectionCreated(this);
        }
 
        state = ConnectionStateEnum.CONNECTED;
        lastReceivedTime = System.currentTimeMillis();
 
        // 延迟1秒发送订阅命令,避免连接未稳定
        new Thread(() -> {
            try {
                Thread.sleep(1000); // 1秒延迟
                commandList.forEach(command -> {
                    send(command);
                });
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
        
    }
 
    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        onError("Unexpected error: " + t.getMessage(), t);
        // 关键:关闭可能存在的响应体
        if (response != null) {
            response.close();
        }
        closeOnError();
    }
 
    private void closeOnError() {
        if (webSocket != null) {
            // 发送错误关闭帧(1011:服务器内部错误)
            webSocket.close(1011, "Error close");
            state = ConnectionStateEnum.CLOSED_ON_ERROR;
            log.error("[Connection error][" + this.getId() + "] Connection is closing due to error");
            webSocket = null; // 置空,避免重复操作
        }
    }
 
    public WebSocket getWebSocket() {
        return webSocket;
    }
 
    public void setWebSocket(WebSocket webSocket) {
        this.webSocket = webSocket;
    }
 
    public Request getOkhttpRequest() {
        return okhttpRequest;
    }
 
    public void setOkhttpRequest(Request okhttpRequest) {
        this.okhttpRequest = okhttpRequest;
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public List<String> getCommandList() {
        return commandList;
    }
 
    public void setCommandList(List<String> commandList) {
        this.commandList = commandList;
    }
 
    public HuobiModelParser getParser() {
        return parser;
    }
 
    public void setParser(HuobiModelParser parser) {
        this.parser = parser;
    }
 
    public ResponseCallback getCallback() {
        return callback;
    }
 
    public void setCallback(ResponseCallback callback) {
        this.callback = callback;
    }
 
    public boolean isAutoClose() {
        return autoClose;
    }
 
    public void setAutoClose(boolean autoClose) {
        this.autoClose = autoClose;
    }
 
    public boolean isAuthNeed() {
        return authNeed;
    }
 
    public void setAuthNeed(boolean authNeed) {
        this.authNeed = authNeed;
    }
 
    public Options getOptions() {
        return options;
    }
 
    public void setOptions(Options options) {
        this.options = options;
    }
 
    public long getDelayInSecond() {
        return delayInSecond;
    }
 
    public void setDelayInSecond(long delayInSecond) {
        this.delayInSecond = delayInSecond;
    }
 
    public String getHost() {
        return host;
    }
 
    public void setHost(String host) {
        this.host = host;
    }
 
    public void setLastReceivedTime(long lastReceivedTime) {
        this.lastReceivedTime = lastReceivedTime;
    }
 
    public void setState(ConnectionStateEnum state) {
        this.state = state;
    }
 
    public String getAuthVersion() {
        return authVersion;
    }
 
    public void setAuthVersion(String authVersion) {
        this.authVersion = authVersion;
    }
 
    @Override
    public String toString() {
        return "HuobiWebSocketConnection [log=" + log + ", lastReceivedTime=" + lastReceivedTime + ", webSocket="
                + webSocket + ", okhttpRequest=" + okhttpRequest + ", state=" + state + ", id=" + id + ", commandList="
                + commandList + ", parser=" + parser + ", callback=" + callback + ", autoClose=" + autoClose
                + ", authNeed=" + authNeed + ", options=" + options + ", delayInSecond=" + delayInSecond + ", host="
                + host + ", authVersion=" + authVersion + "]";
    }
 
}