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>
impl<S: Socket, R: RateLimiter, M: PacketModifier> Server<S, R, M>
Sourcepub fn new(config: Config) -> Server<S, R, M>
pub fn new(config: Config) -> Server<S, R, M>
Creates a new server with the given configuration.
Examples found in repository?
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}
Sourcepub fn bytes_sent(&self) -> u32
pub fn bytes_sent(&self) -> u32
Returns the number of bytes sent over the last second.
Sourcepub fn bytes_received(&self) -> u32
pub fn bytes_received(&self) -> u32
Returns the number of bytes received over the last second.
Sourcepub fn local_addr(&self) -> Result<SocketAddr, Error>
pub fn local_addr(&self) -> Result<SocketAddr, Error>
Returns the local address that the client is sending from.
Sourcepub fn connection(
&mut self,
id: &ConnectionID,
) -> Result<&mut Connection<R, M>, Error>
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?
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}
Sourcepub fn connections(&mut self) -> &mut HashMap<ConnectionID, Connection<R, M>>
pub fn connections(&mut self) -> &mut HashMap<ConnectionID, Connection<R, M>>
Returns a mutable reference to the servers client connections.
Examples found in repository?
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}
Sourcepub fn socket(&mut self) -> Result<&mut S, Error>
pub fn socket(&mut self) -> Result<&mut S, Error>
Returns a mutable reference to the server’s underlying socket.
Sourcepub fn set_config(&mut self, config: Config)
pub fn set_config(&mut self, config: Config)
Overrides the server’s current configuration.
Sourcepub fn listen<A: ToSocketAddrs>(&mut self, addr: A) -> Result<(), Error>
pub fn listen<A: ToSocketAddrs>(&mut self, addr: A) -> Result<(), Error>
Binds the server to listen the specified address.
Examples found in repository?
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}
Sourcepub fn accept_receive(&mut self) -> Result<ServerEvent, TryRecvError>
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?
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}
Sourcepub fn send(&mut self, auto_tick: bool) -> Result<(), Error>
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?
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}
Sourcepub fn shutdown(&mut self) -> Result<(), Error>
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?
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}