public ReceiveFile_Form(FileReceiver receiver, Socket client, HandshakeData data) { InitializeComponent(); this._receiver = receiver; this._client = client; this._data = data; }
/// <summary> /// Initialize handshake process and transfer initial information. /// Actual data will be sent after handshake /// </summary> /// <param name="filename">Name of file to send</param> /// <param name="len">Length of file</param> public void Handshake(string filename, int len) { HandshakeData handshake = new HandshakeData(filename, len); ///Lets now serialize the handshake data. Create a binary ///formatter which will help convert the serializable object ///into binary form BinaryFormatter formatter = new BinaryFormatter(); ///Create a memory string that will hold the serialized data using (MemoryStream stream = new MemoryStream()) { ///Now do the serialization of handshake data formatter.Serialize(stream, handshake); byte[] buffer = new byte[4]; ///Send the length first buffer = AppUtil.ToByteArray((int)stream.Length); ///Send the length first SocketUtil.Send(this._socket, buffer); ///Send the data SocketUtil.Send(this._socket, stream.ToArray()); ///Now get the handshake response HandshakeResponse response = this.GetHandshakeResponse(); ///Close the stream as its not longer needed stream.Close(); ///If casting failed if (response == null) { throw new Exception("The handshake process with receiver failed. Receiver sent an invalid response"); } ///Otherwise we check receivers response. If receiver denied receiving data... if (!response.Continue) { throw new Exception("The destination computer denied to receive data"); } } ///All is well and initial handshake process is completed. /// }
/// <summary> /// Perform handshake /// </summary> /// <remarks>Return true if client is asked to send /// more data, false otherwise</remarks> public HandshakeData Handshake(Socket client) { ///Receive the length byte[] buffer = new byte[4]; SocketUtil.Receive(client, buffer); int incomingLen = AppUtil.FromByteArray(buffer); if (incomingLen <= 0) { ///Nothing to receive. Might be the connection is closing /// return(null); } ///Create a buffer to receive data buffer = new byte[incomingLen]; SocketUtil.Receive(client, buffer); HandshakeData handshake = null; ///Prepeare to deserialize data. /// BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(buffer)) { ///Deserialize handshake = formatter.Deserialize(stream) as HandshakeData; stream.Close(); } ///Cannot deserialize to handshake data if (handshake == null) { ///Close the connection /// this.DiconnectClient(client); } return(handshake); }