Struct TCPMsgServer

Source
pub struct TCPMsgServer<T> {
    pub addr: SocketAddr,
    pub name: String,
    pub connections: Arc<Mutex<HashMap<String, Sender<Option<T>>>>>,
}

Fields§

§addr: SocketAddr§name: String§connections: Arc<Mutex<HashMap<String, Sender<Option<T>>>>>

Implementations§

Source§

impl<T> TCPMsgServer<T>
where T: DeserializeOwned + Serialize + Send + 'static + Clone,

Source

pub fn new(addr: &str, server_name: &str) -> TCPMsgServer<T>

addr is socket address. like: 127.0.0.1:6666. name is the server’s name, to identity which server it is.

Source

pub fn start_server<F>( &self, first_msg: T, process_function: F, ) -> Box<dyn Future<Item = (), Error = ()> + Send + 'static>
where F: FnMut(String, T) -> Vec<(String, T)> + Send + Sync + 'static + Clone,

first_msg is the first message that server send to the client which just connect to server. process_fuction receive a tuple of <client_name, message>, and return a series of tuple of (client_name,message) indicating which message will be sent to which client. Note that if you want to send a message to current client, you should set client_name as a string with 0 length, i.e. “” .

Examples found in repository?
examples/simple_connection.rs (lines 31-34)
29fn server() {
30    let server = create_tcp_server("127.0.0.1:6666", "server");
31    let server_task = server.start_server(0, |client_name, msg| {
32        println!("{}: {}", client_name, msg);
33        vec![(client_name, msg + 1)]
34    });
35    tokio::run(server_task);
36}
More examples
Hide additional examples
examples/master_and_slave.rs (lines 56-64)
53fn master() {
54    use std::{thread, time};
55    let srv = create_tcp_server("127.0.0.1:7777", "master");
56    let master_task = srv.start_server(Message::Start(), |client_name, msg: Message| {
57        println!("master receive {:?} from {}", msg, client_name);
58        println!("sleep");
59        let ten_millis = time::Duration::from_millis(10000);
60        let now = time::Instant::now();
61        thread::sleep(ten_millis);
62        println!("awake");
63        vec![(client_name, Message::Stop())]
64    });
65    tokio::run(master_task);
66}
67
68fn manager() {
69    use futures::sync::mpsc;
70    use std::sync::{Arc, Mutex};
71    let future_task = future::ok(1).and_then(|_| {
72        let srv = create_tcp_server("127.0.0.1:6666", "management_server");
73        let clt = create_tcp_client("127.0.0.1:7777", "management_client");
74        let connections = srv.connections.clone();
75
76        let clt_task = clt.start_client(move |msg: Message| {
77            println!("manager receive {:?} from master", msg);
78            match msg {
79                Message::Stop() => {
80                    for (_, tx) in connections.lock().unwrap().iter_mut() {
81                        (*tx).try_send(Some(0)).unwrap();
82                    }
83                    std::process::exit(0);
84                }
85                _ =>{}
86            }
87            vec![msg]
88        });
89        tokio::spawn(clt_task);
90
91        let srv_task = srv.start_server(1, |client_name, msg: u32| {
92            println!("manager receive {} from {}", msg, client_name);
93            vec![(client_name, msg + 1)]
94        });
95        tokio::spawn(srv_task);
96        Ok(())
97    }).map_err(|e: std::io::Error| println!("{:?}", e));
98    tokio::run(future_task);
99}
examples/transmit_multiple_structs.rs (lines 50-64)
48fn server() {
49    let server = create_tcp_server("127.0.0.1:6666", "server");
50    let server_task = server.start_server(Message::VecOfF32msg(VecOfF32 { vec: vec![] }), |client_name: String, msg: Message| {
51        println!("{}: {:?}", client_name, msg);
52        match msg {
53            Message::VecOfF32msg(vec_of_32) => {
54                if vec_of_32.vec.len() < 10 {
55                    vec![(client_name, Message::VecOfF32msg(vec_of_32))]
56                } else {
57                    vec![(client_name, Message::Endmsg(End))]
58                }
59            }
60            Message::Endmsg(_) => {
61                std::process::exit(0)
62            }
63        }
64    });
65    tokio::run(server_task);
66}

Trait Implementations§

Source§

impl<T: Debug> Debug for TCPMsgServer<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for TCPMsgServer<T>

§

impl<T> RefUnwindSafe for TCPMsgServer<T>

§

impl<T> Send for TCPMsgServer<T>
where T: Send,

§

impl<T> Sync for TCPMsgServer<T>
where T: Send,

§

impl<T> Unpin for TCPMsgServer<T>

§

impl<T> UnwindSafe for TCPMsgServer<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.