1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::io::Error as IOError;
use std::net::{SocketAddr, TcpStream};
use std::ops::{Deref, DerefMut};
use cueball::backend::Backend;
use cueball::connection::Connection;
#[derive(Debug)]
pub struct TcpStreamWrapper {
pub stream: Option<TcpStream>,
addr: SocketAddr,
connected: bool,
}
impl TcpStreamWrapper {
pub fn new(b: &Backend) -> Self {
let addr = SocketAddr::from((b.address, b.port));
TcpStreamWrapper {
stream: None,
addr,
connected: false,
}
}
}
impl Connection for TcpStreamWrapper {
type Error = IOError;
fn connect(&mut self) -> Result<(), Self::Error> {
let stream = TcpStream::connect(&self.addr)?;
self.stream = Some(stream);
self.connected = true;
Ok(())
}
fn close(&mut self) -> Result<(), Self::Error> {
self.stream = None;
self.connected = false;
Ok(())
}
}
impl Deref for TcpStreamWrapper {
type Target = TcpStream;
fn deref(&self) -> &TcpStream {
&self.stream.as_ref().unwrap()
}
}
impl DerefMut for TcpStreamWrapper {
fn deref_mut(&mut self) -> &mut TcpStream {
self.stream.as_mut().unwrap()
}
}