-
Notifications
You must be signed in to change notification settings - Fork 75
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Unify examples to ping-pong example. Minor changes in RemoteAddr
- Loading branch information
Showing
21 changed files
with
247 additions
and
289 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# Ping-Pong example | ||
|
||
This example shows a *clients-server* connection. | ||
The clients send a message every second and the server responds to it. | ||
|
||
You can run both client and server by several transports: `tcp`, `udp`, `ws` (*WebSocket*). | ||
|
||
## Test it! | ||
|
||
Launch the server in a terminal: | ||
``` | ||
cargo run --example ping-pong server <transport> <port> | ||
``` | ||
|
||
Run a client with a name (one client per terminal): | ||
``` | ||
cargo run --example ping-pong client <transport> (<ip>:<port> | <url>) <name> | ||
``` | ||
You can play the disconnections and reconnections using `ctrl-c` over the clients. | ||
|
||
*Note: for *WebSocket* (`ws`), you can specify the address as usually `<ip>:<port>` or as an url: | ||
`ws://domain:port/path` for normal websocket or `wss://domain:port/part` for secure web sockets. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
use super::common::{FromServerMessage, FromClientMessage}; | ||
|
||
use message_io::events::{EventQueue}; | ||
use message_io::network::{Network, NetEvent, Transport, RemoteAddr}; | ||
|
||
use std::time::{Duration}; | ||
|
||
enum Event { | ||
Network(NetEvent<FromServerMessage>), | ||
|
||
// This is a self event called every second. | ||
// You can mix network events with your own events in the EventQueue. | ||
Greet, | ||
} | ||
|
||
pub fn run(transport: Transport, remote_addr: RemoteAddr, name: &str) { | ||
let mut event_queue = EventQueue::new(); | ||
|
||
let network_sender = event_queue.sender().clone(); | ||
let mut network = Network::new(move |net_event| network_sender.send(Event::Network(net_event))); | ||
|
||
let server_id = match network.connect(Transport::Tcp, remote_addr.clone()) { | ||
Ok(server_id) => server_id, | ||
Err(_) => { | ||
return println!("Can not connect to the server by {:?} to {}", transport, remote_addr) | ||
} | ||
}; | ||
|
||
println!("Connect to server by TCP at {}", server_id.addr()); | ||
event_queue.sender().send(Event::Greet); | ||
|
||
loop { | ||
match event_queue.receive() { | ||
Event::Greet => { | ||
let message = FromClientMessage::Greetings(format!("Hi, I am {}", name)); | ||
network.send(server_id, message); | ||
event_queue.sender().send_with_timer(Event::Greet, Duration::from_secs(1)); | ||
} | ||
Event::Network(net_event) => match net_event { | ||
NetEvent::Message(_, message) => match message { | ||
FromServerMessage::CountGreetings(text, count) => { | ||
println!("Server says: '{}' for {} time", text, count) | ||
} | ||
}, | ||
NetEvent::Connected(_) => unreachable!(), // Only generated when listen | ||
NetEvent::Disconnected(_) => return println!("Server is disconnected"), | ||
NetEvent::DeserializationError(_) => (), // Malformed message from the server | ||
}, | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
use serde::{Serialize, Deserialize}; | ||
|
||
#[derive(Serialize, Deserialize)] | ||
pub enum FromClientMessage { | ||
Greetings(String), | ||
} | ||
|
||
#[derive(Serialize, Deserialize)] | ||
pub enum FromServerMessage { | ||
CountGreetings(String, usize), | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
mod common; | ||
mod client; | ||
mod server; | ||
|
||
use message_io::network::{Transport, ToRemoteAddr}; | ||
|
||
use std::net::{ToSocketAddrs}; | ||
|
||
const HELP_MSG: &str = concat!( | ||
"Usage: ping-pong server (tcp | udp | ws) [<port>]\n", | ||
" pong-pong client (tcp | udp | ws) (<ip>:<port>|url) <name>" | ||
); | ||
|
||
pub fn main() { | ||
let args: Vec<String> = std::env::args().collect(); | ||
|
||
let transport = match args.get(2).unwrap_or(&"".into()).as_ref() { | ||
"tcp" => Transport::Tcp, | ||
"udp" => Transport::Udp, | ||
"ws" => Transport::Ws, | ||
_ => return println!("{}", HELP_MSG), | ||
}; | ||
|
||
match args.get(1).unwrap_or(&"".into()).as_ref() { | ||
"client" => match args.get(3) { | ||
Some(remote_addr) => match args.get(4) { | ||
Some(name) => { | ||
let remote_addr = remote_addr.to_remote_addr().unwrap(); | ||
client::run(transport, remote_addr, name); | ||
} | ||
None => return println!("{}", HELP_MSG), | ||
}, | ||
None => return println!("{}", HELP_MSG), | ||
}, | ||
"server" => { | ||
match args.get(3).unwrap_or(&"".into()).parse() { | ||
Ok(port) => { | ||
let addr = ("0.0.0.0", port).to_socket_addrs().unwrap().next().unwrap(); | ||
server::run(transport, addr); | ||
} | ||
Err(_) => return println!("{}", HELP_MSG), | ||
}; | ||
} | ||
_ => return println!("{}", HELP_MSG), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
use super::common::{FromServerMessage, FromClientMessage}; | ||
|
||
use message_io::network::{Network, NetEvent, Endpoint, Transport}; | ||
|
||
use std::collections::{HashMap}; | ||
use std::net::{SocketAddr}; | ||
|
||
struct ClientInfo { | ||
count: usize, | ||
} | ||
|
||
pub fn run(transport: Transport, addr: SocketAddr) { | ||
let (mut network, mut event_queue) = Network::split(); | ||
|
||
let mut clients: HashMap<Endpoint, ClientInfo> = HashMap::new(); | ||
|
||
match network.listen(transport, addr) { | ||
Ok((_resource_id, real_addr)) => println!("TCP Server running at {}", real_addr), | ||
Err(_) => return println!("Can not listening at {}", addr), | ||
} | ||
|
||
loop { | ||
match event_queue.receive() { | ||
// Also you can use receive_timeout | ||
NetEvent::Message(endpoint, message) => match message { | ||
FromClientMessage::Greetings(text) => { | ||
let mut count = clients.get_mut(&endpoint).unwrap().count; | ||
count += 1; | ||
println!("Client ({}) says '{}' {} times", endpoint.addr(), text, count); | ||
let msg = format!("Hi, I hear you for {} time", count); | ||
network.send(endpoint, FromServerMessage::CountGreetings(msg, count)); | ||
} | ||
}, | ||
NetEvent::Connected(endpoint) => { | ||
// Only connection oriented protocols as Tcp or Websocket will generate this event | ||
clients.insert(endpoint, ClientInfo { count: 0 }); | ||
println!( | ||
"Client ({}) connected (total clients: {})", | ||
endpoint.addr(), | ||
clients.len() | ||
); | ||
} | ||
NetEvent::Disconnected(endpoint) => { | ||
// Only connection oriented protocols as Tcp or Websocket will generate this event | ||
clients.remove(&endpoint).unwrap(); | ||
println!( | ||
"Client ({}) disconnected (total clients: {})", | ||
endpoint.addr(), | ||
clients.len() | ||
); | ||
} | ||
NetEvent::DeserializationError(_) => (), // Only if the user send a malformed message. | ||
} | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.