diff options
| author | 魏曹先生 <1992414357@qq.com> | 2025-09-17 12:44:16 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2025-09-17 12:44:16 +0800 |
| commit | bdaab12e6ece9e1c1a0f444ccd890ba47b49789f (patch) | |
| tree | 45cea7cd4a090944884191f2669d66beda23de89 /crates/utils/tcp_connection/src/target_connection.rs | |
| parent | 145eec4d85c634ed582e1d082b846bc70c6dea33 (diff) | |
Update TcpServerTarget
Diffstat (limited to 'crates/utils/tcp_connection/src/target_connection.rs')
| -rw-r--r-- | crates/utils/tcp_connection/src/target_connection.rs | 26 |
1 files changed, 24 insertions, 2 deletions
diff --git a/crates/utils/tcp_connection/src/target_connection.rs b/crates/utils/tcp_connection/src/target_connection.rs index 1e25edd..b03093c 100644 --- a/crates/utils/tcp_connection/src/target_connection.rs +++ b/crates/utils/tcp_connection/src/target_connection.rs @@ -1,4 +1,7 @@ -use tokio::{net::TcpListener, spawn}; +use tokio::{ + net::{TcpListener, TcpSocket}, + spawn, +}; use crate::{ error::TcpTargetError, @@ -13,10 +16,28 @@ where Client: ClientHandle<Server>, Server: ServerHandle<Client>, { + /// Attempts to establish a connection to the TCP server. + /// This function initiates a connection to the server address specified in the target configuration. + /// This is a Block operation. pub async fn connect(&self) -> Result<(), TcpTargetError> { + let addr = self.get_addr(); + let Ok(socket) = TcpSocket::new_v4() else { + return Err(TcpTargetError::from("Create tcp socket failed!")); + }; + let stream = match socket.connect(addr.clone()).await { + Ok(stream) => stream, + Err(e) => { + let err = format!("Connect to `{}` failed: {}", addr, e); + return Err(TcpTargetError::from(err)); + } + }; + let instance = ConnectionInstance::from(stream); + Client::process(instance).await; Ok(()) } + /// Attempts to establish a connection to the TCP server. + /// This function initiates a connection to the server address specified in the target configuration. pub async fn listen(&self) -> Result<(), TcpTargetError> { let addr = self.get_addr(); let listener = match TcpListener::bind(addr.clone()).await { @@ -33,6 +54,7 @@ where }; if cfg.is_once() { + // Process once (Blocked) let (stream, _) = match listener.accept().await { Ok(result) => result, Err(e) => { @@ -44,6 +66,7 @@ where Server::process(instance).await; } else { loop { + // Process multiple times (Concurrent) let (stream, _) = match listener.accept().await { Ok(result) => result, Err(e) => { @@ -57,7 +80,6 @@ where }); } } - Ok(()) } } |
