实现连接服务端

This commit is contained in:
zqm
2026-04-07 15:09:44 +08:00
parent 5915c42f9f
commit 3e64241070
3 changed files with 711 additions and 90 deletions

View File

@@ -2,10 +2,8 @@ use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use tokio::signal;
use tokio::time;
use futures_util::sink::SinkExt;
use futures_util::stream::StreamExt;
use cube_lib::websocket::{WebSocketClient, WebSocketConfig};
/// Updater 自身配置AppData/Updater/config.json
/// 只负责 Updater 自己的行为参数,连接地址从公共 config.json 加载
@@ -100,58 +98,94 @@ fn is_process_running(process_name: &str) -> bool {
count > 0
}
async fn upgrade(server_url: &str, debug_mode: bool) {
if debug_mode {
println!("开始升级检查,连接服务端...");
}
connect_to_websocket(server_url, debug_mode).await;
}
async fn connect_to_websocket(server_url: &str, debug_mode: bool) {
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::{connect_async, tungstenite::Message};
/// 运行 Updater使用 CubeLib 内置的自动重连)
async fn run_updater(debug_mode: bool) {
// 加载初始 URL
let server_url = resolve_ws_url();
if debug_mode {
println!("Connecting to WebSocket server: {}", server_url);
println!("========================================");
println!("Updater 启动 (调试模式)");
println!("服务器地址: {}", server_url);
println!("自动重连: 启用 (指数退避: 1s - 30s)");
println!("========================================");
}
if let Ok(request) = server_url.into_client_request() {
match connect_async(request).await {
Ok((mut ws_stream, _)) => {
if debug_mode {
println!("Connected to WebSocket server");
}
// 创建 WebSocket 配置(启用自动重连)
let config = WebSocketConfig::new(&server_url)
.with_client_type("Updater")
.with_debug(debug_mode)
.with_reconnect(true) // 启用自动重连
.with_reconnect_delay(1000) // 初始延迟 1s
.with_max_reconnect_delay(30000); // 最大延迟 30s
// 注册身份
let app_info = serde_json::json!({
"type": "Updater",
"action": "register"
});
// 创建 WebSocket 客户端
let mut client = WebSocketClient::new(config);
if let Err(e) = ws_stream.send(Message::Text(app_info.to_string())).await {
eprintln!("Failed to send register info: {:?}", e);
} else {
match ws_stream.next().await {
Some(Ok(message)) => {
if debug_mode {
println!("Server response: {:?}", message);
}
}
Some(Err(e)) => {
eprintln!("WebSocket error: {:?}", e);
}
None => {
eprintln!("WebSocket connection closed by server");
}
}
}
}
Err(e) => {
eprintln!("Failed to connect to WebSocket server: {:?}", e);
// 设置连接成功回调
let debug_clone = debug_mode;
client.on_connected(move |url| {
if debug_clone {
println!("[已连接] {}", url);
}
});
// 设置消息接收回调
let debug_for_msg = debug_mode;
client.on_message(move |msg_type, data| {
if debug_for_msg {
println!("[消息] 类型: {}, 数据: {:?}", msg_type, data);
}
// 处理 FileVer 响应
if msg_type == "FileVer" {
if let Some(version) = data.get("version").and_then(|v| v.as_str()) {
println!("[版本] BootLoader.exe 版本: {}", version);
}
}
} else {
eprintln!("Invalid WebSocket URL: {}", server_url);
});
// 设置断开连接回调
let debug_for_disconnect = debug_mode;
client.on_disconnected(move || {
if debug_for_disconnect {
println!("[断开] 连接已断开");
}
});
// 设置错误回调
client.on_error(|error| {
eprintln!("[错误] WebSocket: {}", error);
});
// 设置重连回调 - 在每次重连前重新加载配置
let debug_for_reconnect = debug_mode;
client.on_reconnecting(move |attempt, url_arc| {
if debug_for_reconnect {
println!("[重连] 第 {} 次重连中...", attempt);
}
// 重新读取配置文件并更新 URL
let new_url = resolve_ws_url();
// 更新 CubeLib 内部的 URL
*url_arc.blocking_lock() = new_url.clone();
if debug_for_reconnect {
println!("[配置] 已重新加载,服务器地址: {}", new_url);
}
});
// 连接CubeLib 会自动处理重连)
if debug_mode {
println!("[启动] 开始连接...");
}
// connect() 会等待 websocket_loop 完全结束(包括所有重连)
client.connect().await;
if debug_mode {
println!("[启动] 连接已结束");
}
if debug_mode {
println!("Updater 已停止");
}
}
@@ -165,9 +199,6 @@ async fn main() {
// 加载 Updater 自身配置debug_mode
let config = load_updater_config();
// 从公共 config.json 解析 WebSocket 连接地址
let server_url = resolve_ws_url();
// 非 debug 模式下释放控制台,后台静默运行
if !config.debug_mode {
#[cfg(windows)]
@@ -183,27 +214,10 @@ async fn main() {
}
}
if config.debug_mode {
println!("Updater started in debug mode");
println!("Server URL: {}", server_url);
// 运行 Updater
run_updater(config.debug_mode).await;
let mut interval = time::interval(time::Duration::from_secs(300));
loop {
tokio::select! {
_ = interval.tick() => {
upgrade(&server_url, config.debug_mode).await;
}
_ = signal::ctrl_c() => {
println!("Received Ctrl+C, exiting...");
break;
}
}
}
} else {
let mut interval = time::interval(time::Duration::from_secs(300));
loop {
interval.tick().await;
upgrade(&server_url, config.debug_mode).await;
}
if config.debug_mode {
println!("Updater 已退出");
}
}