/// <summary> /// Receive a message from the server /// </summary> /// <param name="inMessage">the place where the message is going to be stored</param> public void Receive(out HeaderPacketComm header, out string inMessage) { // Create a buffer to store the header byte[] buffer = new byte[HeaderPacketComm.SIZE_HEADER_PACKET]; //Get the header from the socket m_commSocket.Receive(buffer, HeaderPacketComm.SIZE_HEADER_PACKET, 0); // Create a header with the received buffer header = new HeaderPacketComm(buffer); // If the header contains no message, return if (header.m_size == 0) { inMessage = ""; return; } // Creates a buffer to store the message byte[] infoBuffer = new byte[header.m_size]; //Get the actual message from the socket m_commSocket.Receive(infoBuffer, (int)header.m_size, 0); // Create a stream to store the buffer in a int type array uint[] stream = new uint[(int)header.m_size / 4]; // copy the buffer to the array Buffer.BlockCopy(infoBuffer, 0, stream, 0, infoBuffer.Length); // Decrypt the message Cryptography.decrypt(ref stream, m_key); //Get the bytes of the decrypted message byte[] decodedbyteArray = stream.SelectMany(BitConverter.GetBytes).ToArray(); //obtain the string message from the byte array inMessage = System.Text.Encoding.ASCII.GetString(decodedbyteArray).Trim(); }
/// <summary> /// Send a message to the server using the communication protocol /// </summary> /// <param name="messsage">The string representation of the message</param> public uint SendMessage(string messsage, HeaderPacketComm.Command command) { // Creation of the header HeaderPacketComm a = new HeaderPacketComm(); a.m_command = command; lock (syncRoot) { a.m_idResponse = ++m_id_response; } uint lenght = (uint)messsage.Length + 1; uint rest = lenght % 4; a.m_size = rest == 0 ? lenght : lenght + 4 - rest; // Get a byte array of the message byte[] bytes = Encoding.ASCII.GetBytes(messsage); ///Create the stream block to encrypt uint[] stream = new uint[a.m_size / 4]; Buffer.BlockCopy(bytes, 0, stream, 0, bytes.Length); // Encrypt the message with the key of this class Cryptography.encrypt(ref stream, m_key); // Create the final buffer to be sent byte[] buffer = new byte[HeaderPacketComm.SIZE_HEADER_PACKET + a.m_size]; // Copy the header in the buffer Buffer.BlockCopy(a.getByteArray(), 0, buffer, 0, HeaderPacketComm.SIZE_HEADER_PACKET); // Copy the encrypted stream into the buffer Buffer.BlockCopy(stream, 0, buffer, HeaderPacketComm.SIZE_HEADER_PACKET, stream.Length * 4); // Send the buffer to the server m_commSocket.Send(buffer); return(m_id_response); }