falcot/src/client.rs
2025-09-12 00:40:20 +03:00

63 lines
2.1 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// client.rs
//! Клиент для подключения к серверу Falcot
//!
//! Обеспечивает взаимодействие с сервером через TCP соединение
//! с использованием MessagePack для сериализации сообщений.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use crate::common::error::Result;
/// Клиент Falcot
#[allow(dead_code)]
pub struct FalcotClient {
address: String,
}
#[allow(dead_code)]
impl FalcotClient {
pub fn new(address: &str) -> Self {
Self {
address: address.to_string(),
}
}
/// Подключение к серверу и выполнение команды
pub async fn execute_command(&self, command: crate::common::protocol::Command) -> Result<crate::common::protocol::Response> {
let mut socket = tokio::net::TcpStream::connect(&self.address).await
.map_err(|e| crate::common::error::FalcotError::NetworkError(e.to_string()))?;
let (mut reader, mut writer) = socket.split();
// Отправка команды
self.send_message(&mut writer, &command).await?;
// Получение ответа
let response: crate::common::protocol::Response = self.receive_message(&mut reader).await?;
Ok(response)
}
async fn send_message<T: serde::Serialize>(
&self,
writer: &mut (impl AsyncWriteExt + Unpin),
message: &T,
) -> Result<()> {
let bytes = crate::common::protocol::serialize(message)?;
writer.write_all(&bytes).await
.map_err(|e| crate::common::error::FalcotError::NetworkError(e.to_string()))?;
Ok(())
}
async fn receive_message<T: for<'a> serde::Deserialize<'a>>(
&self,
reader: &mut (impl AsyncReadExt + Unpin),
) -> Result<T> {
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer).await
.map_err(|e| crate::common::error::FalcotError::NetworkError(e.to_string()))?;
crate::common::protocol::deserialize(&buffer)
}
}