/// <summary>Connects the client to the server.</summary> /// <param name="serverPort">The port for the server to use for this connection</param> /// <param name="machineName">The host running the server application</param> /// <param name="serverName">The machine name for the server, must match the machine name in the server certificate</param> /// <param name="stream"></param> /// <param name="fileSize"></param> /// <param name="offset"></param> private void Connect(int serverPort, string machineName, string serverName, FileStream stream, long fileSize, long offset) { // Create a TCP/IP client socket. // Set up a temporary connection that is unencrypted, used to transfer the certificates? try { client = new TcpClient(machineName, serverPort); Debug.WriteLine("Client connected."); } catch (ArgumentNullException argExp) { throw new ConnectionException("Host or machine name is null", argExp); } catch (ArgumentOutOfRangeException argORExp) { throw new ConnectionException("The Port is incorrect", argORExp); } catch (SocketException argSExp) { throw new ConnectionException("There is a problem with the Socket", argSExp); } // Create an SSL stream that will close the client's stream. // TODO: The validate server certificate allways returns true // If the validation fails we should ask the user to connect anyway sslStream = new SslStream(client.GetStream(), false, ValidateServerCertificate, null); // The server name must match the name on the server certificate. try { sslStream.AuthenticateAsClient(serverName); } catch (ArgumentNullException argExp) { throw new ConnectionException("Target host is null", argExp); } catch (AuthenticationException argExp) { throw new ConnectionException("The authentication failed and left this object in an unusable state.", argExp); } catch (InvalidOperationException argExp) { throw new ConnectionException("Authentication has already occurred or Server authentication using this SslStream was tried previously org Authentication is already in progress.", argExp); } // When we are connected we can now set up our receive mechanism var readBuffer = new byte[BUFFER_SIZE]; var stateObj = new FileTransferStateObject(); stateObj.fileSize = fileSize; stateObj.sslStream = sslStream; stateObj.target = stream; stateObj.transferBuffer = readBuffer; stateObj.transferOffset = offset; TimeOfLastNotify = DateTime.Now; sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, stateObj); }