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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| static public class ProtocolMech
{
static public ProtocolMessage GetMessage(Socket Src)
{
Int32 size;
Int32 type;
byte[] msg;
if (Src.Available > 2 * sizeof(Int32))
{
Console.WriteLine(Src.Available);
msg = new byte[54];
Src.Receive(msg, 54, SocketFlags.None); //54 = nombre de byte du int32
type = (Int32)ByteArrayToObject(msg);
Console.WriteLine("Av left : " + Src.Available);
msg = new byte[54];
Src.Receive(msg, 54, SocketFlags.None);
size = (Int32)ByteArrayToObject(msg);
Console.WriteLine("Av left 2 : " + Src.Available);
msg = new byte[size];
Src.Receive(msg, size, SocketFlags.None);
Console.WriteLine("Av left final : " + Src.Available);
return new ProtocolMessage(type, msg);
}
else
return null;
}
static public void SendMessage(Int32 Code, object Obj, Socket Dest)
{
MemoryStream _MemoryStream = new MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
byte[] objbuff = ObjectToByteArray(Obj);
byte[] sizebuff = ObjectToByteArray((Int32)objbuff.Length);
byte[] codebuff = ObjectToByteArray(Code);
byte[] buffTotal = new byte[objbuff.Length + sizebuff.Length + codebuff.Length];
Buffer.BlockCopy(codebuff, 0, buffTotal, 0, codebuff.Length);
Buffer.BlockCopy(sizebuff, 0, buffTotal, codebuff.Length, sizebuff.Length);
Buffer.BlockCopy(codebuff, 0, buffTotal, codebuff.Length + sizebuff.Length, codebuff.Length);
Dest.Send(buffTotal, SocketFlags.None);
}
static public object ByteArrayToObject(byte[] _ByteArray)
{
try
{
MemoryStream _MemoryStream = new MemoryStream(_ByteArray);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_MemoryStream.Position = 0;
return _BinaryFormatter.Deserialize(_MemoryStream);
}
catch (Exception _Exception)
{
// Error
throw (_Exception);
}
}
static public byte[] ObjectToByteArray(object Obj)
{
try
{
MemoryStream _MemoryStream = new MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, Obj);
return _MemoryStream.ToArray();
}
catch (Exception _Exception)
{
// Error
throw (_Exception);
}
}
}
public class ProtocolMessage
{
public int Code {set; get;}
public byte[] Object{get; set;}
public ProtocolMessage(int Code, byte[] Obj)
{
this.Code = Code;
this.Object = Obj;
}
} |
Partager