Struct Server

Source
pub struct Server<S: Socket, R: RateLimiter, M: PacketModifier> { /* private fields */ }
Expand description

Implementation of a multi-client low latency socket server.

§Basic Usage

use cobalt::{
    BinaryRateLimiter, Server, Config, NoopPacketModifier, MessageKind, UdpSocket
};

// Create a new server that communicates over a udp socket
let mut server = Server::<UdpSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());

// Make the server listen on port `1234` on all interfaces.
server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");

// loop {

    // Accept incoming connections and fetch their events
    while let Ok(event) = server.accept_receive() {
        // Handle events (e.g. Connection, Messages, etc.)
    }

    // Send a message to all connected clients
    for (_, conn) in server.connections() {
        conn.send(MessageKind::Instant, b"Ping".to_vec());
    }

    // Send all outgoing messages.
    //
    // Also auto delay the current thread to achieve the configured tick rate.
    server.send(true);

// }

// Shutdown the server (freeing its socket and closing all its connections)
server.shutdown();

Implementations§

Source§

impl<S: Socket, R: RateLimiter, M: PacketModifier> Server<S, R, M>

Source

pub fn new(config: Config) -> Server<S, R, M>

Creates a new server with the given configuration.

Examples found in repository?
examples/server.rs (lines 14-19)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn bytes_sent(&self) -> u32

Returns the number of bytes sent over the last second.

Source

pub fn bytes_received(&self) -> u32

Returns the number of bytes received over the last second.

Source

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that the client is sending from.

Source

pub fn connection( &mut self, id: &ConnectionID, ) -> Result<&mut Connection<R, M>, Error>

Returns a mutable reference to the specified client connection.

Examples found in repository?
examples/server.rs (line 32)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn connections(&mut self) -> &mut HashMap<ConnectionID, Connection<R, M>>

Returns a mutable reference to the servers client connections.

Examples found in repository?
examples/server.rs (line 67)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn socket(&mut self) -> Result<&mut S, Error>

Returns a mutable reference to the server’s underlying socket.

Source

pub fn config(&self) -> Config

Returns the server’s current configuration.

Source

pub fn set_config(&mut self, config: Config)

Overrides the server’s current configuration.

Source

pub fn listen<A: ToSocketAddrs>(&mut self, addr: A) -> Result<(), Error>

Binds the server to listen the specified address.

Examples found in repository?
examples/server.rs (line 23)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn accept_receive(&mut self) -> Result<ServerEvent, TryRecvError>

Accepts new incoming client connections from the server’s underlying server and receives and returns messages from them.

Examples found in repository?
examples/server.rs (line 28)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn send(&mut self, auto_tick: bool) -> Result<(), Error>

Sends all queued messages to the server’s underlying client connections.

If auto_tick is specified as true this method will block the current thread for the amount of time which is required to limit the number of calls per second (when called inside a loop) to the server’s configured send_rate.

Examples found in repository?
examples/server.rs (line 74)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}
Source

pub fn shutdown(&mut self) -> Result<(), Error>

Shuts down all of the server’s client connections, clearing any state and freeing the server’s socket.

Examples found in repository?
examples/server.rs (line 81)
11fn main() {
12
13    // Create a new server that communicates over a udp socket
14    let mut server = Server::<
15        UdpSocket,
16        BinaryRateLimiter,
17        NoopPacketModifier
18
19    >::new(Config::default());
20
21    // Make the server listen on port `1234` on all interfaces.
22    println!("[Server] Listening...");
23    server.listen("0.0.0.0:1234").expect("Failed to bind to socket.");
24
25    'main: loop {
26
27        // Accept incoming connections and fetch their events
28        while let Ok(event) = server.accept_receive() {
29            // Handle events (e.g. Connection, Messages, etc.)
30            match event {
31                ServerEvent::Connection(id) => {
32                    let conn = server.connection(&id).unwrap();
33                    println!(
34                        "[Server] Client {} ({}, {}ms rtt) connected.",
35                        id.0,
36                        conn.peer_addr(),
37                        conn.rtt()
38                    );
39
40                },
41                ServerEvent::Message(id, message) => {
42                    let conn = server.connection(&id).unwrap();
43                    println!(
44                        "[Server] Message from client {} ({}, {}ms rtt): {:?}",
45                        id.0,
46                        conn.peer_addr(),
47                        conn.rtt(),
48                        message
49                    );
50
51                },
52                ServerEvent::ConnectionClosed(id, _) | ServerEvent::ConnectionLost(id, _) => {
53                    let conn = server.connection(&id).unwrap();
54                    println!(
55                        "[Server] Client {} ({}, {}ms rtt) disconnected.",
56                        id.0,
57                        conn.peer_addr(),
58                        conn.rtt()
59                    );
60                    break 'main;
61                },
62                _ => {}
63            }
64        }
65
66        // Send a message to all connected clients
67        for (_, conn) in server.connections() {
68            conn.send(MessageKind::Instant, b"Hello from Server".to_vec());
69        }
70
71        // Send all outgoing messages.
72        //
73        // Also auto delay the current thread to achieve the configured tick rate.
74        server.send(true).is_ok();
75
76    }
77
78    println!("[Server] Shutting down...");
79
80    // Shutdown the server (freeing its socket and closing all its connections)
81    server.shutdown().ok();
82
83}

Trait Implementations§

Source§

impl<S: Debug + Socket, R: Debug + RateLimiter, M: Debug + PacketModifier> Debug for Server<S, R, M>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S, R, M> Freeze for Server<S, R, M>
where S: Freeze,

§

impl<S, R, M> RefUnwindSafe for Server<S, R, M>

§

impl<S, R, M> Send for Server<S, R, M>
where S: Send, R: Send, M: Send,

§

impl<S, R, M> Sync for Server<S, R, M>
where S: Sync, R: Sync, M: Sync,

§

impl<S, R, M> Unpin for Server<S, R, M>
where S: Unpin, R: Unpin, M: Unpin,

§

impl<S, R, M> UnwindSafe for Server<S, R, M>
where S: UnwindSafe, R: UnwindSafe, M: UnwindSafe,

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.