2022-07-29 19:55:21 +00:00
|
|
|
use core::fmt;
|
2022-07-29 20:10:49 +00:00
|
|
|
use std::net::SocketAddr;
|
2022-07-29 19:55:21 +00:00
|
|
|
|
|
|
|
use tokio::{
|
|
|
|
io::{self, AsyncReadExt, AsyncWriteExt},
|
2022-07-29 20:10:49 +00:00
|
|
|
net::{TcpStream},
|
2022-07-29 19:55:21 +00:00
|
|
|
};
|
2022-07-01 19:32:20 +00:00
|
|
|
|
2022-06-17 20:32:07 +00:00
|
|
|
/// Max size of a TCP packet
|
2022-06-17 11:43:23 +00:00
|
|
|
pub const MAX_PACKET_LEN: usize = 65536;
|
|
|
|
|
2022-06-17 20:32:07 +00:00
|
|
|
/// TCP Client
|
2022-06-04 11:58:21 +00:00
|
|
|
pub struct Client {
|
2022-06-17 20:32:07 +00:00
|
|
|
/// TCP stream of this client
|
2022-06-04 11:58:21 +00:00
|
|
|
pub stream: TcpStream,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Client {
|
|
|
|
/// Create new Client
|
|
|
|
pub fn new(stream: TcpStream) -> Self {
|
|
|
|
Self { stream }
|
|
|
|
}
|
|
|
|
|
2022-07-28 20:31:10 +00:00
|
|
|
/// Read message/buffer from the client
|
2022-07-01 19:32:20 +00:00
|
|
|
pub async fn read(&mut self) -> anyhow::Result<String> {
|
2022-06-17 11:43:23 +00:00
|
|
|
// allocate an empty buffer
|
|
|
|
let mut buf = [0; MAX_PACKET_LEN];
|
2022-06-04 11:58:21 +00:00
|
|
|
|
2022-06-04 18:10:21 +00:00
|
|
|
// read buffer from stream
|
2022-07-01 19:32:20 +00:00
|
|
|
let len = self.stream.read(&mut buf).await?;
|
2022-06-04 11:58:21 +00:00
|
|
|
|
2022-06-25 19:38:08 +00:00
|
|
|
// select only used bytes from the buffer
|
|
|
|
let recv_buf = &buf[0..len];
|
|
|
|
|
|
|
|
// encode buffer (&[u8]) to a String
|
|
|
|
let decoded = String::from_utf8(recv_buf.to_vec())?;
|
2022-06-04 11:58:21 +00:00
|
|
|
|
2022-06-04 18:10:21 +00:00
|
|
|
Ok(decoded)
|
2022-06-04 11:58:21 +00:00
|
|
|
}
|
|
|
|
|
2022-07-28 20:31:10 +00:00
|
|
|
/// Send message to the client
|
2022-07-29 19:55:21 +00:00
|
|
|
pub async fn send<S>(&mut self, content: S) -> io::Result<()>
|
|
|
|
where
|
2022-07-29 20:10:49 +00:00
|
|
|
S: ToString + fmt::Display,
|
2022-07-29 19:55:21 +00:00
|
|
|
{
|
2022-06-04 18:10:21 +00:00
|
|
|
// add a new line at the end of the content
|
|
|
|
let content = format!("{content}\n\r");
|
|
|
|
|
|
|
|
// send message
|
2022-07-01 19:32:20 +00:00
|
|
|
self.stream.write_all(content.as_bytes()).await
|
2022-06-04 11:58:21 +00:00
|
|
|
}
|
2022-07-29 20:10:49 +00:00
|
|
|
|
|
|
|
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
|
|
|
|
self.stream.peer_addr()
|
|
|
|
}
|
2022-06-04 11:58:21 +00:00
|
|
|
}
|