59 lines
1.5 KiB
Rust
59 lines
1.5 KiB
Rust
use crate::tcp::errors::StreamClientError;
|
|
use std::io::{Read, Write};
|
|
use std::net::TcpStream;
|
|
|
|
#[derive(Clone)]
|
|
pub struct ConnectOptions {
|
|
pub ip: String,
|
|
pub port: i32,
|
|
}
|
|
|
|
impl ConnectOptions {
|
|
pub fn new(ip: String, port: i32) -> ConnectOptions {
|
|
ConnectOptions { ip, port }
|
|
}
|
|
}
|
|
|
|
pub struct StreamClient {
|
|
connect_options: ConnectOptions,
|
|
}
|
|
|
|
impl StreamClient {
|
|
pub fn new(connection_options: ConnectOptions) -> StreamClient {
|
|
StreamClient {
|
|
connect_options: connection_options,
|
|
}
|
|
}
|
|
|
|
pub fn send(&self, bytes: Vec<u8>) -> Result<Vec<u8>, StreamClientError> {
|
|
match TcpStream::connect(format!(
|
|
"{}:{}",
|
|
self.connect_options.ip, self.connect_options.port
|
|
)) {
|
|
Ok(mut stream) => match stream.write(&bytes) {
|
|
Ok(size) => {
|
|
let mut buf = Vec::with_capacity(size);
|
|
match stream.read_to_end(&mut buf) {
|
|
// TODO: what happens if there is nothing to read?
|
|
Ok(_) => Ok(buf.to_vec()),
|
|
Err(_) => Err(StreamClientError::Read),
|
|
}
|
|
}
|
|
Err(_) => Err(StreamClientError::Write),
|
|
},
|
|
Err(e) => {
|
|
eprintln!("{e}");
|
|
Err(StreamClientError::Connect)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
mod errors {
|
|
pub enum StreamClientError {
|
|
Connect,
|
|
Write,
|
|
Read,
|
|
}
|
|
}
|