Guest User

Untitled

a guest
Jun 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. extern crate tokio_tcp;
  2. extern crate tokio_udp;
  3. extern crate byteorder;
  4.  
  5. using std::any::Any;
  6.  
  7. struct NetOutput;
  8. struct NetInput;
  9. struct NetConnection;
  10.  
  11. trait Packet {
  12. fn encode(&self);
  13. fn decode(&mut self);
  14. }
  15.  
  16. trait NetHandler {
  17. fn on_connection(&mut self, c: &NetConnection);
  18. fn on_disconnect(&mut self, c: &NetConnection);
  19. fn on_received(&mut self, c: &NetConnection, p: &Packet);
  20. }
  21.  
  22. struct ExamplePacket {
  23. message: String
  24. }
  25.  
  26. impl Packet for ExamplePacket {
  27. fn encode(&self, o: &mut NetOutput) {
  28. o.write_string(self.message);
  29. }
  30.  
  31. fn decode(&mut self, i: &mut NetInput) {
  32. self.message = i.read_string();
  33. }
  34. }
  35.  
  36. struct ExampleHandler;
  37.  
  38. impl NetHandler for ExampleHandler {
  39. fn on_connection(&mut self, c: &NetConnection) {
  40. println!("Connection!");
  41. }
  42.  
  43. fn on_disconnect(&mut self, c: &NetConnection) {
  44. println!("Disconnect!");
  45. }
  46.  
  47. fn on_received<T: Any>(&mut self, c: &NetConnection, p: &Any) {
  48. let val = p as &Any;
  49.  
  50. match val.downcast_ref::<ExamplePacket>() {
  51. Some(p) => {
  52. println!("Received ExamplePacket with {}", p.message);
  53. },
  54. None => { }
  55. }
  56. }
  57. }
  58.  
  59. fn main() {
  60. let mut registry = PacketRegistry::new();
  61. registry.add(0x00, Box::new(ExamplePacket));
  62. let s = TcpServer::new(SocketAddr::from(([127, 0, 0, 1], 25565)), &registry, &handler);
  63. s.begin().unwrap();
  64. }
Add Comment
Please, Sign In to add comment