1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class Packet
{
public static String PacketSize(Int32 Size)
{
Char c1 = Convert.ToChar(Size / Convert.ToInt32(Math.Pow(2, 16)));
Size -= Convert.ToInt32(Math.Pow(2, 16)) * Convert.ToInt32(c1);
Char c2 = Convert.ToChar(Size / Convert.ToInt32(Math.Pow(2, 8)));
Size -= Convert.ToInt32(Math.Pow(2, 8)) * Convert.ToInt32(c2);
Char c3 = Convert.ToChar(Size);
String test = Convert.ToString(c1) + Convert.ToString(c2) + Convert.ToString(c3);
return (test);
}
public static Int32 PacketSize(String Size)
{
return (Convert.ToInt32(Size[0]) * Convert.ToInt32(Math.Pow(2, 16)) + Convert.ToInt32(Size[1]) * Convert.ToInt32(Math.Pow(2, 8)) + Convert.ToInt32(Size[2]));
}
public static Boolean ParsePacket(ref String Pack, ref String Destinataire, ref String Commande, ref String Content)
{
String current = Pack;
if (current.Length > 3)
{
Int32 Size = Packet.PacketSize(current.Substring(0, 3));
MessageBox.Show(Convert.ToString(Size));
if (current.Length < 3 + Size)
return (false);
String cur = current.Substring(3, Size);
Pack = current.Substring(3 + Size);
Size = Packet.PacketSize(cur.Substring(0, 3));
String Header = cur.Substring(3, Size);
String[] tab = Header.Split('\0');
Destinataire = tab[0];
Commande = tab[1];
Content = cur.Substring(Size + 3);
return (true);
}
return (false);
}
public static String BuildPacket(String Destinataire, String Commande, String Content)
{
String pack = Packet.PacketSize(Destinataire.Length + Commande.Length + Content.Length + 3 + 1) + Packet.PacketSize(Destinataire.Length + Commande.Length + 1) + Destinataire + "\0" + Commande + Content;
return (pack);
}
public static String BuildPacket(String Destinataire, String Commande)
{
String pack = Packet.PacketSize(Destinataire.Length + Commande.Length + 3 + 1) + Packet.PacketSize(Destinataire.Length + Commande.Length + 1) + Destinataire + "\0" + Commande;
return (pack);
}
} |