2022-06-04 11:58:21 +00:00
|
|
|
#![allow(clippy::unused_io_amount)]
|
|
|
|
|
2022-06-04 19:34:53 +00:00
|
|
|
use std::{
|
|
|
|
io::{self, Read, Write},
|
2022-06-04 11:58:21 +00:00
|
|
|
net::TcpStream,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub struct Client {
|
|
|
|
pub stream: TcpStream,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Client {
|
|
|
|
/// Create new Client
|
|
|
|
pub fn new(stream: TcpStream) -> Self {
|
|
|
|
Self { stream }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Read message/buffer from Client
|
2022-06-05 21:13:14 +00:00
|
|
|
pub fn read(&mut self) -> anyhow::Result<String> {
|
2022-06-04 18:10:21 +00:00
|
|
|
// allocate an empty buffer of length 1024 bytes
|
2022-06-04 11:58:21 +00:00
|
|
|
let mut buf = [0; 1024];
|
|
|
|
|
2022-06-04 18:10:21 +00:00
|
|
|
// read buffer from stream
|
2022-06-04 19:34:53 +00:00
|
|
|
self.stream.read(&mut buf)?;
|
2022-06-04 11:58:21 +00:00
|
|
|
|
2022-06-04 18:10:21 +00:00
|
|
|
// encode &[u8] to a String and replace null spaces (empty `\0` bytes)
|
|
|
|
let decoded = String::from_utf8(buf.to_vec())?.replace('\0', "");
|
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
|
|
|
}
|
|
|
|
|
|
|
|
/// Send message to Client
|
2022-06-05 21:13:14 +00:00
|
|
|
pub fn send(&mut self, content: &str) -> io::Result<()> {
|
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-06-04 19:34:53 +00:00
|
|
|
self.stream.write_all(content.as_bytes())
|
2022-06-04 11:58:21 +00:00
|
|
|
}
|
|
|
|
}
|