Struct grubbnet::Server

source ·
pub struct Server { /* private fields */ }

Implementations§

source§

impl Server

source

pub fn host(ip: &str, port: u16, connection_limit: usize) -> Result<Server>

Begin hosting a TCP server.

Examples found in repository?
examples/simple_server.rs (line 62)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn num_connections(&self) -> usize

Get the current number of connections.

Examples found in repository?
examples/simple_server.rs (line 81)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn connection_limit(&self) -> usize

Get the maximum number of connections allowed.

Examples found in repository?
examples/simple_server.rs (line 82)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn drain_incoming_packets(&mut self) -> Vec<(Token, Packet)>

Drain any incoming packets and return them.

Examples found in repository?
examples/simple_server.rs (line 108)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn kick(&mut self, connection_token: Token) -> Result<()>

Kick a connection from the server.

Examples found in repository?
examples/simple_server.rs (line 121)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn send(&mut self, recipient: PacketRecipient, packet: impl PacketBody)

Send a packet. This function will box the packet, then queue it to be sent on the next server tick.

Examples found in repository?
examples/simple_server.rs (line 129)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}
source

pub fn send_boxed( &mut self, recipient: PacketRecipient, packet_boxed: Box<dyn PacketBody> )

Send a boxed packet. Similar to send, but this is moreuseful when you have a boxed packet already and don’t want to cast it to a concrete type before sending it.

source

pub fn tick(&mut self) -> Vec<ServerEvent>

Runs a network tick, which sends/receives packets based on socket readiness, as well as accepts new connections.

Examples found in repository?
examples/simple_server.rs (line 74)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn main() -> Result<()> {
    // Begin hosting a TCP server
    let mut server = Server::host("127.0.0.1", 7667, 32)?;
    println!("Hosting on 127.0.0.1:7667...");

    // We are going to keep track of the # of pings we receive from each client, and kick them
    // after they have sent a certain amount.
    let mut ping_counters: HashMap<Token, u32> = HashMap::new();

    loop {
        // Sleep for a lil bit so we don't hog the CPU
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Run the network tick and process any events it generates
        for event in server.tick().iter() {
            match event {
                ServerEvent::ClientConnected(token, addr) => {
                    println!(
                        "Client {} connected from {} ({}/{})",
                        token.0,
                        addr.ip(),
                        server.num_connections(),
                        server.connection_limit(),
                    );
                }
                ServerEvent::ClientDisconnected(token) => {
                    println!("Client {} disconnected.", token.0);
                }
                ServerEvent::ConnectionRejected(addr) => {
                    println!(
                        "Rejected connection from {} (Connection limit reached)",
                        addr.ip(),
                    );
                }
                ServerEvent::ReceivedPacket(token, byte_count) => {
                    println!(
                        "Received packet from client {} ({} bytes)",
                        token.0, byte_count
                    );
                }
                ServerEvent::SentPacket(token, byte_count) => {
                    println!("Sent packet to client {} ({} bytes)", token.0, byte_count);
                }
                _ => eprintln!("Unhandled ServerEvent!"),
            }
        }

        // Process incoming packets
        for (token, packet) in server.drain_incoming_packets().iter() {
            match packet.header.id {
                0x00 => {
                    let packet = PingPacket::deserialize(&packet.body);
                    println!("Got ping from client {}: {}", token.0, packet.unwrap().msg);

                    // Increment the ping counter for this client
                    let counter = ping_counters.entry(*token).or_insert(0);
                    *counter += 1;

                    if *counter >= 5 {
                        // Kick the client when they reach 5 pings.
                        println!("Client {} sent 5 pings. Kicking them.", token.0);
                        server.kick(*token)?;

                        ping_counters.remove_entry(token);
                    } else {
                        // Otherwise just send a ping response (pong).
                        let pong = PongPacket {
                            msg: "Pong!".to_owned(),
                        };
                        server.send(PacketRecipient::Single(*token), pong);
                    }
                }
                _ => eprintln!("Unhandled packet! id: {}", packet.header.id),
            }
        }
    }

    Ok(())
}

Auto Trait Implementations§

§

impl !RefUnwindSafe for Server

§

impl Send for Server

§

impl Sync for Server

§

impl Unpin for Server

§

impl !UnwindSafe for Server

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.