shitty message client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 regels
2.4 KiB

  1. // namespacing
  2. use crate::Result;
  3. use async_std::net::TcpStream;
  4. use async_std::prelude::*;
  5. use futures_util::io::ReadHalf;
  6. use std::convert::TryInto;
  7. mod join;
  8. pub use join::Join;
  9. mod message;
  10. pub use message::Message;
  11. /// structured [packet type byte][four bytes of packet length][contents of packet]
  12. pub struct NetworkPacket(Vec<u8>);
  13. impl std::convert::Into<NetworkPacket> for Packet {
  14. fn into(self) -> NetworkPacket {
  15. let mut contents: Vec<u8> = Vec::new();
  16. // packet type byte
  17. contents.push(self.packet_type as u8);
  18. // write the packet length
  19. let contents_length = self.packet_contents.len() as u32;
  20. contents.extend_from_slice(&contents_length.to_le_bytes());
  21. // write the rest of the contents
  22. contents.extend_from_slice(&self.packet_contents);
  23. NetworkPacket(contents)
  24. }
  25. }
  26. pub trait Sendable {
  27. fn to_packet(self) -> Packet;
  28. fn from_packet(packet: Packet) -> Self;
  29. }
  30. /// contains data to be turned into a network packet or into a more specific packet
  31. pub struct Packet {
  32. pub packet_type: PacketType,
  33. packet_contents: Vec<u8>,
  34. }
  35. impl Packet {
  36. /// create a new packet
  37. pub fn new(packet_type: PacketType, packet_contents: Vec<u8>) -> Self {
  38. Self { packet_type, packet_contents }
  39. }
  40. /// read a packet from a tcpstream
  41. pub async fn read(stream: &mut ReadHalf<TcpStream>) -> Result<Option<Packet>> {
  42. let mut info_buf = [0u8; 5];
  43. let check = stream.read(&mut info_buf).await?;
  44. if check == 0 {
  45. return Ok(None);
  46. }
  47. let packet_type = PacketType::from_u8(info_buf[0]).unwrap();
  48. let length = u32::from_le_bytes(info_buf[1..5].try_into().unwrap()) as usize;
  49. let mut contents: Vec<u8> = vec![0; length];
  50. stream.read(&mut contents).await?;
  51. Ok(Some(Packet::new(packet_type, contents)))
  52. }
  53. /// write a packet to the tcpstream
  54. pub async fn write(self, stream: &mut TcpStream) -> Result<()> {
  55. let network_packet: NetworkPacket = self.into();
  56. stream.write(&network_packet.0).await?;
  57. Ok(())
  58. }
  59. }
  60. /// represent the specific packet type
  61. #[repr(u8)]
  62. pub enum PacketType {
  63. Message = 0,
  64. Join = 1,
  65. }
  66. impl PacketType {
  67. /// returns the PacketType if the u8 is a valid packet type
  68. pub fn from_u8(packet_type: u8) -> Option<Self> {
  69. match packet_type {
  70. 0 => Some(Self::Message),
  71. _ => None,
  72. }
  73. }
  74. }