using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClientUdp { public enum Commande { POST, GET, HELP, QUIT, STOPSERVEUR, SUBSCRIBE, SUBSCRIBEv2, UNSUBSCRIBE }; public enum CommandeType { REQUETE, REPONSE }; class ChatMessage { public const int bufferSize = 1500; public const int pseudoSize = 30; public Commande commande; // commande public CommandeType commandeType; // type (Requête/Réponse) public int dataSize; // taille de la donnée public String pseudo; // pseudo public String data; // données de la commande public ChatMessage(Commande commande, CommandeType type, String pseudo, String data) { this.commande = commande; this.commandeType = type; this.dataSize = data.Length; this.pseudo = pseudo; this.data = data; } public ChatMessage(byte[] buffer) { int i = 2; if (buffer.Length > bufferSize) throw new ArgumentException("Buffer trop grand"); this.commande = (Commande)buffer[0]; this.commandeType = (CommandeType)buffer[1]; while (i < pseudoSize && Encoding.ASCII.GetString(buffer, i, 1) != "\0") { this.pseudo += Encoding.ASCII.GetString(buffer, i, 1); } i = pseudoSize + 2; while (i < bufferSize && Encoding.ASCII.GetString(buffer, i, 1) != "\0") { this.data += Encoding.ASCII.GetString(buffer, i, 1); } } public byte[] GetBytes() { byte[] res = new byte[bufferSize]; res[0] = (byte)this.commande; res[1] = (byte)this.commandeType; //encodage du pseudo et ajout au tableau de bytes Encoding.ASCII.GetBytes(this.pseudo, 0, this.pseudo.Length, res, 2); //encodage du message et ajout au tableau de bytes Encoding.ASCII.GetBytes(this.data, 0, this.data.Length, res, pseudoSize + 2); return res; } public override string ToString() { return "[" + commande + "," + commandeType + ",\"" + pseudo + "\"," + dataSize + ",\"" + data + "\"]"; } } }