nexus/client/src/networking/plugin.rs

101 lines
4.4 KiB
Rust

use bevy::app::{App, Plugin};
use bevy::prelude::{Commands, EventReader, ResMut};
use bytes::Bytes;
use crossbeam_channel::{Receiver, Sender};
use qp2p::{Config, Endpoint};
use tokio::runtime::Runtime;
use bevy_add_events_macro::add_events;
use crate::networking::{event, resource};
use crate::networking::resource::NetworkingRuntimeHandlerSignals::KILL;
use std::{
env,
net::{Ipv4Addr, SocketAddr},
time::Duration,
};
use std::sync::Arc;
use bincode::config;
use serde_json::Value;
pub struct NetworkingPlugin;
impl Plugin for NetworkingPlugin {
fn build(&self, app: &mut App) {
add_events!(app, event::ConnectToServer);
app.add_startup_system(setup_networking_runtime);
app.add_system(connection_added);
app.add_system(server_client_connection_handler);
}
}
pub fn setup_networking_runtime(mut commands: Commands) {
commands.insert_resource(resource::NetworkingRuntime(Runtime::new().expect("networking runtime needs to be init'd to work!")));
commands.insert_resource(Arc::new(resource::ServerConnection::new()));
commands.insert_resource(Arc::new(resource::NetworkingRuntimeMessenger::new()));
}
/// sends events based on things received from the server connection
pub fn server_client_connection_handler(mut commands: Commands, mut server_cx: ResMut<Arc<resource::ServerConnection>>) {
for message in server_cx.rx.try_iter() {
let (string, size) = bincode::decode_from_slice(message.as_ref(), config::standard()).unwrap();
let str: &str = string;
println!("message is: {}", str);
}
}
pub fn connection_added(
mut server_cx_events: EventReader<event::ConnectToServer>,
mut server_connection: ResMut<Arc<resource::ServerConnection>>,
mut net_runtime: ResMut<resource::NetworkingRuntime>,
mut net_runtime_messenger: ResMut<Arc<resource::NetworkingRuntimeMessenger>>) {
//We wanna get the last connection request, or just end this function if we don't have any.
let socket_address = match server_cx_events.iter().last() {
None => {return;}
Some(sock) => {sock.clone()}
}.0.clone();
//Then we wanna kill whatever is currently running
net_runtime_messenger.cx.send(KILL).expect("unable to kill networking runtime");
//Then we setup our new connection
let mut config = Config::default();
config.idle_timeout = None; //change this so we can actually do something based on it.
let server_connection = server_connection.clone();
let net_runtime_messenger = net_runtime_messenger.clone();
net_runtime.0.spawn(async move {
let endpoint = Endpoint::new_client(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)), config)
.expect("unable to setup endpoint for client connection");
println!("setup endpoint");
let (_connection, mut incoming_connection) = endpoint.connect_to(&socket_address).await.expect("error connecting to server");
println!("connected");
let _x = net_runtime_messenger.rx.try_recv().unwrap(); //have to flush.
while net_runtime_messenger.rx.is_empty() {
let recived = incoming_connection.next().await.unwrap().unwrap();
server_connection.cx.send(recived).unwrap();
}
});
}
// match socket_addr.iter().last().clone() {
// None => {}
// Some(sock_addr) => {
// let sock_addr = sock_addr.0.clone();
// //First we want to shutdown the currently running network if there is one.
// networking_runtime_handler.cx.send(KILL).expect("unable to kill networking runtime");
// //setup the client endpoint with no timeout so it can wait as long as needed
// let mut config = Config::default();
// config.idle_timeout = None; //change this so we can actually do something based on it.
// let endpoint = Endpoint::new_client(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)), config)
// .expect("unable to setup endpoint for client connection");
// let net_runtime_handler = networking_runtime_handler.clone();
// let server_cx = server_connection.clone();
// //Then we spawn the new runtimes
// networking_runtime.0.spawn(async move {
// let future = endpoint.connect_to(&sock_addr);
// let (connection, mut incoming_connection) = future.await.unwrap();
// while net_runtime_handler.rx.is_empty() {
// server_cx.cx.send(incoming_connection.next().await.unwrap().unwrap()).unwrap();
// }
// });
// }
// }