pub struct Server { /* private fields */ }
Implementations§
source§impl Server
impl Server
sourcepub fn host(ip: &str, port: u16, connection_limit: usize) -> Result<Server>
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(())
}
sourcepub fn num_connections(&self) -> usize
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(())
}
sourcepub fn connection_limit(&self) -> usize
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(())
}
sourcepub fn drain_incoming_packets(&mut self) -> Vec<(Token, Packet)>
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(())
}
sourcepub fn kick(&mut self, connection_token: Token) -> Result<()>
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(())
}
sourcepub fn send(&mut self, recipient: PacketRecipient, packet: impl PacketBody)
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(())
}
sourcepub fn send_boxed(
&mut self,
recipient: PacketRecipient,
packet_boxed: Box<dyn PacketBody>
)
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.
sourcepub fn tick(&mut self) -> Vec<ServerEvent>
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(())
}