messages.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use serde::{Deserialize, Serialize};
  2. #[derive(Serialize, Deserialize)]
  3. pub struct Msg {
  4. pub nonce: u16,
  5. pub command: Command,
  6. }
  7. #[derive(Serialize, Deserialize)]
  8. pub enum Command {
  9. Hello(String),
  10. Goodbye,
  11. Update(f32, f32),
  12. }
  13. impl Msg {
  14. pub fn parse<R>(reader: R) -> Option<Msg>
  15. where R: std::io::Read
  16. {
  17. match serde_json::from_reader(reader) {
  18. Ok(r) => Some(r),
  19. Err(_err) => None,
  20. }
  21. }
  22. pub fn from_slice(slice: &[u8]) -> Msg {
  23. serde_json::from_slice(slice).unwrap()
  24. }
  25. pub fn emit<W>(&self, writer: W)
  26. where W: std::io::Write
  27. {
  28. serde_json::to_writer(writer, self).unwrap()
  29. }
  30. }
  31. pub struct Connection {
  32. nonce: u16,
  33. tcp_addr: String,
  34. udp_sock: std::net::UdpSocket,
  35. }
  36. impl Connection {
  37. pub fn new(name: &str, host: &str, port: u32) -> Self {
  38. let nonce = rand::random();
  39. let tcp_addr = format!("{}:{}", host, port);
  40. let stream = std::net::TcpStream::connect(&tcp_addr).unwrap();
  41. Msg {
  42. nonce: nonce,
  43. command: Command::Hello(name.to_string()),
  44. }.emit(stream);
  45. let udp_addr = format!("{}:{}", host, port+1);
  46. let udp_sock = std::net::UdpSocket::bind("0.0.0.0:9898").unwrap();
  47. udp_sock.connect(udp_addr);
  48. Connection { nonce, tcp_addr, udp_sock }
  49. }
  50. pub fn update(&self, x: f32, y: f32) {
  51. let update = Msg {
  52. nonce: self.nonce,
  53. command: Command::Update(x, y),
  54. };
  55. let buf = serde_json::ser::to_vec(&update).unwrap();
  56. self.udp_sock.send(&buf).unwrap();
  57. }
  58. pub fn goodbye(&self) {
  59. let stream = std::net::TcpStream::connect(&self.tcp_addr).unwrap();
  60. Msg {
  61. nonce: self.nonce,
  62. command: Command::Goodbye,
  63. }.emit(stream);
  64. }
  65. }