/*
|
package com.nq.ws;
|
|
import org.java_websocket.client.WebSocketClient;
|
import org.java_websocket.handshake.ServerHandshake;
|
import org.json.JSONObject;
|
import java.net.URI;
|
import java.net.URISyntaxException;
|
import java.time.LocalDateTime;
|
import java.time.format.DateTimeFormatter;
|
import java.util.Timer;
|
import java.util.TimerTask;
|
|
public class WebSocketClientExample {
|
|
public static void main(String[] args) {
|
try {
|
URI uri = new URI("ws://api-mx-ws.js-stock.top"); // 替换为实际的 WebSocket 地址
|
String key = "key:91kktoeVjh96PB3hnovv:7"; // 替换为实际密钥和国家id
|
|
//URI uri = new URI("ws://api-us-v2-ws.js-stock.top");
|
//String key = "key:SIjHECiI3cIVfHXwsLsL:5";
|
WebSocketClient client = new WebSocketClient(uri) {
|
private Timer heartbeatTimer;
|
@Override
|
public void onOpen(ServerHandshake handshakedata) {
|
System.out.println("已连接到服务器");
|
send(key);
|
// 启动心跳定时器
|
heartbeatTimer = new Timer();
|
heartbeatTimer.schedule(new TimerTask() {
|
@Override
|
public void run() {
|
send("heartbeat");
|
}
|
}, 0, 3000); // 每3秒发送一次心跳消息
|
}
|
@Override
|
public void onMessage(String message) {
|
// 获取当前时间并格式化为字符串
|
LocalDateTime now = LocalDateTime.now();
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
String timestamp = now.format(formatter);
|
try {
|
if (message.contains("身份验证成功") || message.contains("pong") || message.contains("身份验证失败")
|
|| message.contains("ws")) {
|
System.out.println(timestamp + "" + message);
|
return;
|
}
|
System.out.println("mex" + message);
|
*/
|
/*JSONObject json = new JSONObject(message);
|
String pid = json.optString("pid");
|
String last = json.optString("last");
|
// 输出 pid 和 last
|
System.out.println(timestamp + " pid: " + pid + "价格: " + last);*//*
|
|
} catch (Exception e) {
|
System.err.println("处理消息时发生错误: " + message);
|
}
|
}
|
@Override
|
public void onClose(int code, String reason, boolean remote) {
|
System.out.println("连接关闭: " + reason);
|
if (heartbeatTimer != null) {
|
heartbeatTimer.cancel(); // 取消心跳定时器
|
}
|
// 尝试重新连接
|
try {
|
System.out.println("尝试重新连接...");
|
Thread.sleep(10000); // 10秒后尝试重新连接
|
connect(); // 重新连接
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}
|
}
|
@Override
|
public void onError(Exception ex) {
|
System.err.println("发生错误: " + ex.getMessage());
|
}
|
};
|
client.connect();
|
} catch (URISyntaxException e) {
|
e.printStackTrace();
|
}
|
}
|
|
}
|
*/
|