Exemple #1
0
        private static void RunServer(ProgramOptions options)
        {
            var listener = new TcpListener(options.Host, options.Port);
            listener.Start();
            var display = new Display(options, listener.GetPort()) {Delay = .5.Seconds()};
            display.Refresh();

            try
            {

                var files = options.Directory.EnumerateFiles("*", SearchOption.AllDirectories);
                var buffer = new byte[Extensions.DefaultStreamCopyBufferSize];

                using (var it = files.GetEnumerator())
                {
                    using (var client = listener.AcceptTcpClient())
                    using (var netStream = client.GetStream())
                    using (var compStream = options.Compression.HasValue
                            ? new DeflateStream(netStream, options.Compression.Value)
                            : null)
                    using(var clearWriter = new BinaryWriter((Stream)compStream ?? netStream))
                    using (var aes = CreateAes(options))
                    using (var enc = aes?.CreateEncryptor())
                    using (var cryptoStream = aes != null
                            ? new CryptoStream((Stream)compStream ?? netStream, enc, CryptoStreamMode.Write)
                            : null)
                    using (var writer = new BinaryWriter(cryptoStream ?? (Stream)compStream ?? netStream))
                    {
                        if (aes != null)
                            clearWriter.Write(aes.IV);

                        display.Stopwatch.Start();

                        while (it.MoveNext())
                        {
                            var file = it.Current;
                            display.CurrentFile = new FileProgress(
                                file.GetRelativePathFrom(options.Directory),
                                file.Length).Do(x => x.Stopwatch.Start());
                            var path = file.GetRelativePathFrom(options.Directory);

                            writer.Write(path);
                            writer.Write(file.Length);

                            using (var fileStream = file.OpenRead())
                                fileStream.CopyTo(writer.BaseStream, file.Length, buffer,
                                    b =>
                                    {
                                        display.ByteCount += (display.CurrentFile.BytesTransferred = b);
                                        display.Refresh();
                                    });

                            display.FileCount++;
                            display.Refresh();
                        }
                    }
                }
            }
            finally
            {
                listener.Stop();
            }
        }