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
use std::net::TcpStream;
use std::io::{ErrorKind,Error};
use crate::ic_types::{IcConnection,IcPacket,IcCommand};

/// The Client interface struct for IntelCache. Used to interact with the server.
pub struct IcClient { con: IcConnection }
impl IcClient {
	/// Connect to `ip` address
	///
	/// Note: the address is in ipv4 format. No ports.
	///
	/// Returns a client or an error (if couldn't connect).
	pub fn connect(ip: &str) -> Result<IcClient,Error> {
		let con = TcpStream::connect(ip.to_owned()+":64209");
		if let Ok(c) = con {
			return Ok(IcClient { con: IcConnection::new(c) });
		} else {
			return Err(Error::new(ErrorKind::Other,"Failed to connect."));
		}
	}

	/// `send_cmd` will send a command to the server
	///
	/// Returns an [`IcPacket`] from the server
	pub fn send_cmd(&mut self,c: &mut IcCommand) -> IcPacket {
		if self.con.check_connection() {
			//println!("[DEBUG#IcServer.handle_client] SENDING ICP_PACKET : {} ({:?})",(&c).to_ic_packet().header.as_ref().unwrap_or(&"None".to_string()),(&c).to_ic_packet().body.as_ref().unwrap_or(&Vec::new()).len());
			self.con.send_packet(c.to_ic_packet()).unwrap(); 
			let retp = self.con.get_packet().unwrap_or(IcPacket::new_empty());
			//println!("[DEBUG#IcServer.handle_client] RECIEVING IC_PACKET : {} ({:?})",(&retp).header.as_ref().unwrap_or(&"None".to_string()),(&retp).body.as_ref().unwrap_or(&Vec::new()).len());
			return retp;
		} else {
			return IcPacket::new_empty();
		}
	}
}