-
Notifications
You must be signed in to change notification settings - Fork 74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to use endpoint #125
Comments
Hi @git2013vb, The 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. |
Sure :)
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 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 think I posted all the code related the error. Let me know if I miss something. |
I re read my issue and probably I have to write |
Hi, If I have seen it well, you're trying to move the Looking in detail, the GUI closure is not using the |
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:) |
I close the issue. Feel free to reopen it if needed. |
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 usehandler.network().send(server_id, &output_data);
But I have no access to theserver_id
/endpoint
because the point where my button trigger is inside atwinit
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 becauseEndpoint
doesn't haveClone
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.
The text was updated successfully, but these errors were encountered: