-
Notifications
You must be signed in to change notification settings - Fork 24
/
WebSocketJavaExample.java
97 lines (42 loc) · 2.39 KB
/
WebSocketJavaExample.java
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
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.*;
@ClientEndpoint
public class WebSocketJavaExample {
private Session session;
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
this.session = session;
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Disconnected from server");
}
@OnError
public void onError(Throwable throwable) {
System.err.println("Error: " + throwable.getMessage());
}
public void sendMessage(String message) throws Exception {
this.session.getBasicRemote().sendText(message);
}
public static void main(String[] args) throws Exception, URISyntaxException, DeploymentException, IOException, IllegalArgumentException, SecurityException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
//token申请:https://github.com/CTradeExchange/free-quote/blob/master/token%E7%94%B3%E8%AF%B7.md
//官网:https://alltick.co
URI uri = new URI("wss://quote.tradeswitcher.com/quote-stock-b-ws-api?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806"); // Replace with your websocket endpoint URL
WebSocketJavaExample client = new WebSocketJavaExample();
container.connectToServer(client, uri);
// Send messages to the server using the sendMessage() method
//如果希望长时间运行,除了需要发送订阅之外,还需要修改代码,定时发送心跳,避免连接断开,具体查看接口文档
client.sendMessage("{\"cmd_id\": 22002, \"seq_id\": 123,\"trace\":\"3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806\",\"data\":{\"symbol_list\":[{\"code\": \"700.HK\",\"depth_level\": 5},{\"code\": \"UNH.US\",\"depth_level\": 5}]}}");
// Wait for the client to be disconnected from the server (or until the user presses Enter)
System.in.read(); // Wait for user input before closing the program
}
}