68 lines
2 KiB
Rust
68 lines
2 KiB
Rust
use bevnet::{
|
|
client::{ClientAppExt, ClientPlugin, ServerConnection},
|
|
server::{ClientListener, ServerAppExt, ServerPlugin},
|
|
};
|
|
use bevy::prelude::*;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct Ping;
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct Pong;
|
|
|
|
fn start_server(mut commands: Commands, keys: Res<Input<KeyCode>>) {
|
|
if keys.just_pressed(KeyCode::B) {
|
|
println!("Starting server...");
|
|
match ClientListener::bind("127.0.0.1:8000") {
|
|
Ok(listener) => {
|
|
commands.insert_resource(listener);
|
|
println!("Server started");
|
|
}
|
|
Err(e) => println!("Failed to start server: {}", e),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn connect(mut commands: Commands, keys: Res<Input<KeyCode>>) {
|
|
if keys.just_pressed(KeyCode::C) {
|
|
println!("Connecting to server...");
|
|
match ServerConnection::connect("127.0.0.1:8000") {
|
|
Ok(connection) => {
|
|
commands.insert_resource(connection);
|
|
println!("Connected to server");
|
|
}
|
|
Err(e) => println!("Failed to connect: {}", e),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn send_ping(connection: Option<Res<ServerConnection>>, keys: Res<Input<KeyCode>>) {
|
|
if keys.just_pressed(KeyCode::S) {
|
|
println!("Sending ping...");
|
|
if let Some(connection) = connection {
|
|
connection.send(Ping);
|
|
println!("Ping sent");
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_plugin(ServerPlugin)
|
|
.add_system(start_server)
|
|
.add_server_packet_handler::<Ping, _>(|entity, connection, _, _| {
|
|
println!("Received ping from {:?}", entity);
|
|
connection.send(Pong);
|
|
println!("Sent pong to {:?}", entity);
|
|
})
|
|
.add_plugin(ClientPlugin)
|
|
.add_system(connect)
|
|
.add_client_packet_handler::<Pong, _>(|_, _| {
|
|
println!("Received pong");
|
|
})
|
|
.add_system(send_ping)
|
|
.run();
|
|
}
|