1use std::cell::RefCell;
2use std::time::Duration;
3use mco::net::TcpStream;
4use codec::{BinCodec, Codecs};
5use stub::ClientStub;
6use mco::std::errors::Result;
7use serde::de::DeserializeOwned;
8use serde::Serialize;
9use balance::RpcClient;
10
11#[derive(Debug)]
12pub struct Client {
13 pub addr: String,
14 pub codec: Codecs,
15 pub stub: ClientStub,
16 pub stream: RefCell<TcpStream>,
17}
18
19impl Client {
20 pub fn dial(addr: &str) -> std::io::Result<Self> {
21 let address = addr.to_string();
22 let stream = TcpStream::connect(addr)?;
23 Ok(Self {
24 addr: address,
25 codec: Codecs::BinCodec(BinCodec {}),
26 stub: ClientStub::new(),
27 stream: RefCell::new(stream),
28 })
29 }
30
31 pub fn set_timeout(mut self, timeout: Duration) -> Self {
33 self.stub.timeout = timeout;
34 self
35 }
36
37 pub fn get_timeout(&self) -> &Duration {
39 &self.stub.timeout
40 }
41
42 pub fn call<Arg, Resp>(&self, func: &str, arg: Arg) -> Result<Resp> where Arg: Serialize, Resp: DeserializeOwned {
43 let resp: Resp = self.stub.call(func, arg, &self.codec, &mut *self.stream.borrow_mut())?;
44 return Ok(resp);
45 }
46}
47
48impl RpcClient for Client {
49 fn addr(&self) -> &str {
50 self.addr.as_str()
51 }
52}