ugly_smart_lib/
net_pub.rs

1//! src/tcp_pub.rs
2//!
3//! `tcp_pub` 是一个公共文件
4//!
5//! 它包含以下结构。
6//! - ConnectionState 会话管理
7//! - spawn_and_log_error 产生一个异步任务接口
8//! - TcpFrameTrait 客户端和服务端特质
9//! - 一些公共声明
10
11use super::smart_pub::{MpscAsyncSender, StdArc, StdResult};
12
13pub const SERVER_KEY: &'static str = "Server";
14pub const CLIENT_KEY: &'static str = "Client";
15
16/// 连接状态
17#[derive(Debug)]
18pub enum EConnectionState<T> {
19    /// 正在连接
20    Connecting,
21    /// 正常连接
22    Running(MpscAsyncSender<T>),
23    // Running(MpscAsyncSender<(String, Vec<u8>)>),
24    /// 中断
25    Interrupt,
26    /// 停止
27    Stoped,
28}
29
30impl Default for EConnectionState<Vec<u8>> {
31    fn default() -> Self {
32        EConnectionState::Stoped
33    }
34}
35
36impl Default for EConnectionState<(String, Vec<u8>)> {
37    fn default() -> Self {
38        EConnectionState::Stoped
39    }
40}
41
42/// 服务类型
43#[derive(Clone, Copy, PartialEq)]
44pub enum ServiceType {
45    /// 服务器
46    Server,
47    /// 客户端
48    Client,
49}
50
51impl Default for ServiceType {
52    fn default() -> Self {
53        Self::Client
54    }
55}
56
57impl From<i32> for ServiceType {
58    fn from(value: i32) -> Self {
59        match value {
60            0 => ServiceType::Server,
61            1 => ServiceType::Client,
62            _ => Self::Client,
63        }
64    }
65}
66
67impl From<String> for ServiceType {
68    fn from(value: String) -> Self {
69        match &value as &str {
70            SERVER_KEY => ServiceType::Server,
71            CLIENT_KEY => ServiceType::Client,
72            _ => ServiceType::Client,
73        }
74    }
75}
76
77impl std::fmt::Display for ServiceType {
78    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
79        match self {
80            Self::Server => {
81                write!(f, "{}", SERVER_KEY)
82            }
83            Self::Client => {
84                write!(f, "{}", CLIENT_KEY)
85            }
86        }
87    }
88}
89
90impl std::fmt::Debug for ServiceType {
91    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
92        match self {
93            Self::Server => {
94                write!(f, "{}", SERVER_KEY)
95            }
96            Self::Client => {
97                write!(f, "{}", CLIENT_KEY)
98            }
99        }
100    }
101}
102
103/// 回调函数特质
104pub trait INetCallBack<T>
105where
106    Self: Send + Sync,
107{
108    /// 数据回调接口
109    ///
110    /// # Arguments
111    /// * 'self' 自身对象的共享指针
112    /// * 'data' 收到的数据
113    /// * 'handle' 额外参数
114    /// * 'serv_type' 服务类型
115    ///
116    /// # Returns
117    /// * 无
118    fn data_callback(self: StdArc<Self>, data: Vec<u8>, handle: String, serv_type: ServiceType);
119
120    /// 连接状态回调接口
121    ///
122    /// # Arguments
123    /// * 'self' 自身对象的共享指针
124    /// * 'handle' 额外参数
125    /// * 'state' 连接状态
126    /// * 'serv_type' 服务类型
127    ///
128    /// # Returns
129    /// * 无
130    fn state_callback(
131        self: StdArc<Self>,
132        // &mut self,
133        handle: String,
134        state: EConnectionState<T>,
135        serv_type: ServiceType,
136    );
137}
138
139impl std::fmt::Display for dyn INetCallBack<Vec<u8>> {
140    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
141        write!(f, "CallBackTrait Display")
142    }
143}
144
145impl std::fmt::Debug for dyn INetCallBack<Vec<u8>> {
146    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
147        write!(f, "CallBackTrait Debug")
148    }
149}
150
151impl std::fmt::Display for dyn INetCallBack<(String, Vec<u8>)> {
152    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
153        write!(f, "CallBackTrait Display")
154    }
155}
156
157impl std::fmt::Debug for dyn INetCallBack<(String, Vec<u8>)> {
158    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
159        write!(f, "CallBackTrait Debug")
160    }
161}
162
163/// 客户端和服务端特质
164pub trait INetwork {
165    // type ReturnFuture; // = impl std::future::Future<Output = StdResult<()>> + Send;
166
167    /// 实现开启服务或连接
168    ///
169    /// # Arguments
170    /// * 'self' 自身对象的共享指针
171    ///
172    /// # Returns
173    /// * future trait,用于异步调用
174    fn start(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;
175
176    /// 实现停止服务或断开连接
177    ///
178    /// # Arguments
179    /// * 'self' 自身对象的共享指针
180    ///
181    /// # Returns
182    /// * future trait,用于异步调用
183    fn stop(self: StdArc<Self>) -> impl std::future::Future<Output = StdResult<()>> + Send;
184}
185
186/*
187/// 实现 输出连接状态 打印
188///
189/// # Arguments
190/// * 'addr' - 连接地址
191/// * 'state' - 连接状态
192///
193/// # Returns
194/// * 无
195///
196/// # Examples
197/// ```rust
198/// use smart_lib::tcp_pub;
199/// fn main() {
200/// 	let e:tcp_pub::EConnectionState = tcp_pub::EConnectionState::Connecting;
201/// 	let addr:String = "127.0.0.1:80".to_string();
202/// 	tcp_pub::inspect_connection_state(&addr, &e);
203/// }
204/// ```
205///
206pub fn inspect_connection_state(addr: &String, state: &EConnectionState) {
207    match state {
208        EConnectionState::Connecting => tklog::info!(addr, "connection connecting."),
209        EConnectionState::Running(_) => tklog::info!(addr, "connection normal running."),
210        EConnectionState::Interrupt => tklog::error!(addr, "connection interrrupt."),
211        EConnectionState::Stoped => tklog::fatal!(addr, "connection stoped."),
212    }
213}
214*/
215
216/// 产生一个异步任务
217pub fn spawn_and_log_error<F>(fut: F) -> tokio::task::JoinHandle<()>
218where
219    F: std::future::Future<Output = StdResult<()>> + Send + 'static,
220{
221    tokio::spawn(async move {
222        if let Err(e) = fut.await {
223            tracing::error!(e)
224        }
225    })
226}