首次连接回调

This commit is contained in:
zqm
2026-04-07 15:44:30 +08:00
parent 6cbd9e1e30
commit 7a832698c2
2 changed files with 7 additions and 5 deletions

View File

@@ -30,4 +30,4 @@
pub mod websocket;
pub use websocket::{WebSocketClient, WebSocketConfig, WebSocketMessage};
pub use websocket::{WebSocketClient, WebSocketConfig, WebSocketMessage, OutgoingMessage, ConnectionStatus};

View File

@@ -2,6 +2,7 @@
use crate::websocket::{WebSocketConfig, WebSocketMessage, WebSocketError};
use futures_util::{SinkExt, StreamExt};
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::{mpsc, Mutex};
use tokio::time::Duration;
@@ -60,7 +61,8 @@ pub type SentCallback = Arc<dyn Fn(String, Value) + Send + Sync>;
pub type ReconnectingCallback = Arc<dyn Fn(u32, Arc<tokio::sync::Mutex<String>>) + Send + Sync>;
/// Callback triggered on first successful connection (before any reconnect)
/// Arguments: (url, send_fn) - send_fn can be called to send messages
pub type FirstConnectCallback = Arc<dyn Fn(String, Arc<Mutex<Option<mpsc::Sender<OutgoingMessage>>>>) + Send + Sync>;
/// Note: This is an async callback - return a boxed Future
pub type FirstConnectCallback = Arc<dyn Fn(String, Arc<Mutex<Option<mpsc::Sender<OutgoingMessage>>>>) -> Pin<Box<dyn std::future::Future<Output = ()> + Send + Sync + 'static>> + Send + Sync>;
/// WebSocket client with event-driven architecture
pub struct WebSocketClient {
@@ -198,10 +200,10 @@ impl WebSocketClient {
}
/// Set callback for first successful connection (before any reconnect)
/// This is called only on the first connection, allowing the app to send initial messages
/// This is an async callback - the returned Future will be awaited
pub fn on_first_connect<F>(&mut self, callback: F) -> &mut Self
where
F: Fn(String, Arc<Mutex<Option<mpsc::Sender<OutgoingMessage>>>>) + Send + Sync + 'static,
F: Fn(String, Arc<Mutex<Option<mpsc::Sender<OutgoingMessage>>>>) -> Pin<Box<dyn std::future::Future<Output = ()> + Send + Sync + 'static>> + Send + Sync + 'static,
{
self.on_first_connect = Some(Arc::new(callback));
self
@@ -468,7 +470,7 @@ impl WebSocketClient {
// Call on_first_connect callback (only on first connection, not on reconnect)
if is_first {
if let Some(ref callback) = on_first_connect {
callback(url.to_string(), sender);
callback(url.to_string(), sender).await;
}
}