flare_core/server/transports/mod.rs
1//! 服务端传输协议模块
2//!
3//! 提供多种传输协议的服务端实现:
4//! - QUIC:基于 QUIC 协议的服务端
5//! - WebSocket:基于 WebSocket 协议的服务端
6//! - Hybrid:混合服务端,支持多种协议
7//!
8//! 同时定义服务端的标准 trait 接口
9
10use crate::common::error::Result;
11use crate::common::protocol::Frame;
12use async_trait::async_trait;
13
14/// 连接处理器
15///
16/// 处理单个客户端连接的逻辑
17#[async_trait]
18pub trait ConnectionHandler: Send + Sync {
19 /// 处理接收到的 Frame 消息
20 ///
21 /// # 参数
22 /// - `frame`: 接收到的 Frame
23 /// - `connection_id`: 连接 ID
24 ///
25 /// # 返回
26 /// 如果需要回复,返回 `Some(Frame)`,否则返回 `None`
27 async fn handle_frame(&self, frame: &Frame, connection_id: &str) -> Result<Option<Frame>>;
28
29 /// 处理连接建立事件
30 ///
31 /// # 参数
32 /// - `connection_id`: 连接 ID
33 async fn on_connect(&self, connection_id: &str) -> Result<()> {
34 let _ = connection_id;
35 Ok(())
36 }
37
38 /// 处理连接断开事件
39 ///
40 /// # 参数
41 /// - `connection_id`: 连接 ID
42 async fn on_disconnect(&self, connection_id: &str) -> Result<()> {
43 let _ = connection_id;
44 Ok(())
45 }
46}
47
48/// 服务端标准接口
49///
50/// 实现此 trait 以创建自定义服务端实现
51///
52/// 注意:消息发送和连接管理功能请使用 `ServerHandle` trait
53///
54/// # 示例
55///
56/// ```rust
57/// use async_trait::async_trait;
58/// use flare_core::server::Server;
59/// use flare_core::common::error::Result;
60///
61/// struct MyCustomServer {
62/// // 自定义服务器实现
63/// }
64///
65/// #[async_trait]
66/// impl Server for MyCustomServer {
67/// async fn start(&mut self) -> Result<()> {
68/// // 实现启动逻辑
69/// Ok(())
70/// }
71///
72/// async fn stop(&mut self) -> Result<()> {
73/// // 实现停止逻辑
74/// Ok(())
75/// }
76///
77/// fn is_running(&self) -> bool {
78/// true
79/// }
80/// }
81/// ```
82#[async_trait]
83pub trait Server: Send + Sync {
84 /// 启动服务器
85 ///
86 /// # 返回
87 /// 启动成功返回 `Ok(())`,失败返回错误
88 async fn start(&mut self) -> Result<()>;
89
90 /// 停止服务器
91 ///
92 /// # 返回
93 /// 停止成功返回 `Ok(())`,失败返回错误
94 async fn stop(&mut self) -> Result<()>;
95
96 /// 检查服务器运行状态
97 ///
98 /// # 返回
99 /// 如果正在运行返回 `true`,否则返回 `false`
100 fn is_running(&self) -> bool;
101}
102
103mod common;
104#[cfg(any(feature = "websocket", feature = "quic", feature = "tcp"))]
105pub mod hybrid;
106#[cfg(feature = "quic")]
107pub mod quic;
108pub mod server_core;
109#[cfg(feature = "tcp")]
110pub mod tcp;
111#[cfg(feature = "websocket")]
112pub mod websocket;
113
114// 重新导出常用类型
115#[cfg(any(feature = "websocket", feature = "quic", feature = "tcp"))]
116pub use hybrid::HybridServer;
117#[cfg(feature = "quic")]
118pub use quic::QUICServer;
119#[cfg(feature = "tcp")]
120pub use tcp::TCPServer;
121#[cfg(feature = "websocket")]
122pub use websocket::WebSocketServer;