lemunozm / message-io

Fast and easy-to-use event-driven network library.
Apache License 2.0
1.11k stars 74 forks source link

How to use endpoint #125

Closed git2013vb closed 2 years ago

git2013vb commented 2 years ago

Hi, I have a question , most likely is a simple/silly one but I'm new in Rust so I hope you can answer me:

I run the ping-pong example and it work. But in order to use it in my project I need to access to client/server endpoint from outside listener loop because I want to keep just one connection all the time between client and server.

Outside the ping-pong example I have my project (I use a game engine which use winit as crate) where I have my UI with a button that I made in order to send a message when I click on it. I was going to use handler.network().send(server_id, &output_data); But I have no access to the server_id / endpoint because the point where my button trigger is inside at winit crate loop (aka UI).

Because the UI loop consume(move) the data - it use a closure - it give an error when I try to save endpoint in a external struct because Endpoint doesn't have Clone trait.

But I'm not confident to make changes yet in your code :).

So my question is: which solution/option do you suggest? I tried my best to explain my problem but tell me if you need more info.

lemunozm commented 2 years ago

Hi @git2013vb,

The Endpoint implements both, Copy and Clone traits so you should be able to copy/clone it.

Maybe you can share a minor example (it is not necessary that it compiles) to see the structure of your code and to know exactly what is happening.

git2013vb commented 2 years ago

Sure :) I have a workspace where inside I have: server , client, my_lib. Currently the problem is in the client because I haven't done anything in server. First of all the error (main.rs in client workspace)

error[E0382]: assign to part of moved value: `client.client_network`
   --> client/src/main.rs:100:9
    |
100 |         client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------------^^^^^^^^^^^
    |         |                                                                 |
    |         |                                                                 value moved here
    |         value partially assigned here after move
    |
    = note: move occurs because `client.client_network` has type `desert_edge_lib::network::Network`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `client.client_network`
   --> client/src/main.rs:107:20
    |
98  |       thread::spawn(|| {
    |                     -- value moved into closure here
99  |           // connect to server
100 |           client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    |                                                                             --------------------- variable moved due to use in closure
...
107 |       event_loop.run(move |event, _, control_flow| {
    |  ____________________^
108 | |         match event {
109 | |             Event::MainEventsCleared => {
110 | |                 // This main game loop - it has fixed time step which means that game
...   |
217 | |         }
218 | |     });
    | |_____^ value used here after move
    |
    = note: move occurs because `client.client_network` has type `desert_edge_lib::network::Network`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0382`.

then its code:


struct Client {
    login_screen: LoginScreen,
    client_network: Network,
    // tcp_stream: Result<TcpStream, eyre::Report>,
    is_exit: bool,
}
impl Client {
    fn new(engine: &mut Engine) -> Self {
        let (signal_handler, signal_listener) = node::split::<Signal>();
        Self {
            client_network: Network {
                signal_handler,
                signal_listener,
                client_endpoint:None,
                // client_listener: ClientListener {
                //     endpoint: Endpoint::from_listener(resource_id, addr),
                //     socket_address,
                // },
            },
            login_screen: LoginScreen::new(engine, P_400X350),
            is_exit: false,
        }
    }
}
fn main() {
    tracing_subscriber::registry().with(LogLayer).init();
    Log::set_verbosity(MessageKind::Warning); // remove [INFO] messages from Fyrox
                                              // rust_i18n::set_locale("it");
    trace!("{}", LOG_START);
    //================================
    let event_loop = EventLoop::new();
    // Create window builder first.
    let window_builder = WindowBuilder::new()
        .with_title("DesertEdge")
        .with_resizable(true);

    let serialization_context = Arc::new(SerializationContext::new());
    let mut engine = Engine::new(EngineInitParams {
        window_builder,
        resource_manager: ResourceManager::new(serialization_context.clone()),
        serialization_context,
        events_loop: &event_loop,
        vsync: true,
    })
    .unwrap();

    let mut client = Client::new(&mut engine);

    // Define game loop variables.
    let clock = Instant::now();
    let fixed_timestep = 1.0 / 60.0;
    let mut elapsed_time = 0.0;
    thread::spawn(|| {
        // connect to server
        client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    });

    // Finally run our event loop which will respond to OS and window events and update
    // engine state accordingly. Engine lets you to decide which event should be handled,
    // this is minimal working example if how it should be.

    event_loop.run(move |event, _, control_flow| {
        match event {
            Event::MainEventsCleared => {
                // This main game loop - it has fixed time step which means that game
                // code will run at fixed speed even if renderer can't give you desired
                // 60 fps.
                let mut dt = clock.elapsed().as_secs_f32() - elapsed_time;
                while dt >= fixed_timestep {
                    dt -= fixed_timestep;
                    elapsed_time += fixed_timestep;

                    // ************************
                    // ************************
                    // Put your game logic here.
                    // ************************
                    // ************************
                    if client.is_exit {
                        *control_flow = ControlFlow::Exit;
                    }

                    // It is very important to update the engine every frame!
                    engine.update(fixed_timestep);
                }

                // It is very important to "pump" messages from UI. Even if don't need to
                // respond to such message, you should call this method, otherwise UI
                // might behave very weird.
                while let Some(message) = engine.user_interface.poll_message() {
                    // ************************
                    // ************************
                    // Put your data model synchronization code here. It should
                    // take message and update data in your game according to
                    // changes in UI.
                    // ************************
                    // ************************
                    match message.data() {
                        Some(ButtonMessage::Click) => {
                            if message.destination() == client.login_screen.quit_button_handle {
                                // network::close_connection(&self);
                                trace!("Used exit button to close");
                                log_quit();
                                client.is_exit = true
                            }
                            if message.destination() == client.login_screen.login_button_handle {
                                info!("Login Pressed");
                                let data = b"hello world";
                                // let endpoint = client.client_network.signal_handler.network();
                                // client.client_network.signal_handler.network().send(
                                //     client.client_network.client_listener.endpoint,
                                //     data,
                                // );
                                &client
                                    .client_network
                                    .signal_handler
                                    .network()
                                    .send(client.client_network.client_endpoint.unwrap(), data);
                            }
                        }
                        _ => (),
                    }
                }

                // Rendering must be explicitly requested and handled after RedrawRequested event is received.
                engine.get_window().request_redraw();
            }
            Event::RedrawRequested(_) => {
                // Run renderer at max speed - it is not tied to game code.
                engine.render().unwrap();
            }
            Event::WindowEvent { event, .. } => {
                match event {
                    WindowEvent::CloseRequested => {
                        log_quit();
                        *control_flow = ControlFlow::Exit
                    }
                    WindowEvent::Resized(size) => {
                        // It is very important to handle Resized event from window, because
                        // renderer knows nothing about window size - it must be notified
                        // directly when window size has changed.
                        if let Err(e) = engine.set_frame_size(size.into()) {
                            Log::writeln(
                                MessageKind::Error,
                                format!("Unable to set frame size: {:?}", e),
                            );
                        }
                        // engine.user_interface.send_message(WidgetMessage::width(
                        //     self.client_main_screen.grid_handle,
                        //     MessageDirection::ToWidget,
                        //     size.width as f32,
                        // ));
                        // engine.user_interface.send_message(WidgetMessage::height(
                        //     self.client_main_screen.grid_handle,
                        //     MessageDirection::ToWidget,
                        //     size.height as f32,
                        // ));
                        debug!("Resized");
                    }
                    // Handle rest of events here if necessary.
                    _ => (),
                }

                // It is very important to "feed" user interface (UI) with events coming
                // from main window, otherwise UI won't respond to mouse, keyboard, or any
                // other event.
                if let Some(os_event) = translate_event(&event) {
                    engine.user_interface.process_os_event(&os_event);
                }
            }
            // Continue polling messages from OS.
            _ => *control_flow = ControlFlow::Poll,
        }
    });
    // old way .....
    // let framework_game = Framework::<Game>::new()?;
    // let framework_game = framework_game.title("DesertEdge");
    // framework_game.run();
}
pub fn log_quit() {
    trace!("{}", LOG_QUIT);
}

Then the Network struct (in my lib in the same workspace ./network/mod.rs):

pub struct Network {
    pub signal_handler: NodeHandler<Signal>,
    pub signal_listener: NodeListener<Signal>,
    pub client_endpoint: Option<Endpoint>,
}

Then the fn where I use to connect to the server(./network/mod.rs):

pub fn connection_to_server(client_network: Network) -> ClientListener {
    debug!("connection to server");
    let transport = Transport::Tcp;
    let remote_addr = (String::from("127.0.0.1:10000")).to_remote_addr().unwrap();
    let (endpoint, socket_address) = client_network
        .signal_handler
        .network()
        .connect(transport, remote_addr.clone())
        .unwrap();
    client_network
        .signal_listener
        .for_each(move |node_event| match node_event {
            NodeEvent::Network(net_event) => match net_event {
                NetEvent::Accepted(_, _) => unreachable!(), // Only generated when a listener accepts
                NetEvent::Connected(_, established) => {
                    if established {
                        trace!(
                            "Connected to server at {} by {}",
                            endpoint.addr(),
                            transport
                        );
                        info!("Client identified by local port: {}", socket_address.port());
                        client_network.signal_handler.signals().send(Signal::Greet);
                        info!("Sent Greet");
                    } else {
                        trace!(
                            "Can not connect to server at {} by {}",
                            socket_address,
                            transport
                        )
                    }
                }
                NetEvent::Message(_, input_data) => {
                    let message: FromServerMessage = bincode::deserialize(&input_data).unwrap();
                    match message {
                        FromServerMessage::Pong(count) => {
                            println!("Pong from server: {} times", count)
                        }
                        FromServerMessage::UnknownPong => println!("Pong from server"),
                    }
                }
                NetEvent::Disconnected(_) => {
                    trace!("Server is disconnected");
                    client_network.signal_handler.stop();
                }
            },
            NodeEvent::Signal(signal) => match signal {
                Signal::Greet => {
                    let message: FromClientMessage = FromClientMessage::Ping;
                    let output_data = bincode::serialize(&message).unwrap();
                    client_network
                        .signal_handler
                        .network()
                        .send(endpoint, &output_data);
                    // client_network_handler
                    //     .signals()
                    //     .send_with_timer(Signal::Greet, Duration::from_secs(1));
                }
            },
        });
    ClientListener {
        endpoint,
        socket_address,
    }
}

The game engine is Fyrox I tried to set #[derive(Clone)] in Network struct but after that he error switched to the Enpoint.


   --> desert_edge_lib/src/network/mod.rs:20:5
    |
17  | #[derive(Clone)]
    |          ----- in this derive macro expansion
...
20  |     pub signal_listener: NodeListener<Signal>,
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `NodeListener<network::Signal>`
    |
note: required by `clone`
   --> /home/vale/.rustup/toolchains/1.57.0-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/clone.rs:122:5
    |
122 |     fn clone(&self) -> Self;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^
    = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.

I think I posted all the code related the error. Let me know if I miss something. Thanks :)

git2013vb commented 2 years ago

I re read my issue and probably I have to write NodeListener Instead of point out the problem to the Endpoint I'm not 100% sure, because I did a lot of try and repeat in my code :).

lemunozm commented 2 years ago

Hi, If I have seen it well, you're trying to move the Network struct you have created into two different closures. This struct is neither copy nor clone, this is the reason you are getting the error.

Looking in detail, the GUI closure is not using the NodeListener for anything, so that instance should be only moved to the first spawned thread. The NodeHandler is clonable and you can send two instances to the closures. Regarding the endpoint, if you want to write its value and then read it from the other closure, I would wrap it into an Arc<Mutex<Option<Endpoint>>>. In that way, you can share the value among the threads/closures.

git2013vb commented 2 years ago

Thank you for your suggestions. In effect was too advanced for me to came up with that solution :)

Now I have to digest all of it :). Ill take some time I guess.

Thank you again:)

lemunozm commented 2 years ago

I close the issue. Feel free to reopen it if needed.