Exemplo n.º 1
0
        private void SendFile(DirectoryItem file, string relativePath)
        {
            if (file.IsFolder)
            {
                throw new FailedSendingException("Cannot send folder as file.");
            }


            // Send file info
            byte[] infoBuffer = new byte[1 + 8 + 1024]; // instruction + fileSize + name (max 256 chars and 4 bytes per char)
            infoBuffer[0] = (byte)TTInstruction.Transfer_FileInfo;

            byte[] sizeBytes = BitConverter.GetBytes(file.Size);
            Array.Copy(sizeBytes, 0, infoBuffer, 1, sizeBytes.Length);

            string fullName = $"{relativePath}{file.Name}";

            byte[] fullNameBytes = Encoding.UTF8.GetBytes(fullName);
            Array.Copy(fullNameBytes, 0, infoBuffer, 1 + 8, fullNameBytes.Length);

            TrySend(infoBuffer, true);


            // Send file
            long bytesToSend              = file.Size;
            bool useEncryption            = serverEncryptor != null;
            TransferProgressReport report = new TransferProgressReport();

            report.TotalBytes   = totalBytes;
            report.ActiveItem   = file.Name;
            report.CurrentBytes = 0;
            report.IsSender     = true;
            transferProgress.Report(report);
            WriteResult result;

            using (FileStream fs = File.OpenRead(file.Path))
            {
                int bufferSize = 0;
                while (bytesToSend > 0)
                {
                    try
                    {
                        bufferSize = (int)Math.Min(bytesToSend, maxBufferSize);

                        byte[] buffer = new byte[bufferSize];
                        fs.Read(buffer, 0, bufferSize);

                        if (useEncryption)
                        {
                            buffer = serverEncryptor.AESEncryptBytes(buffer);
                        }

                        result = client.Send(buffer);
                        if (result.Status != WriteResultStatus.Success)
                        {
                            throw new FailedSendingException("Could not send data.");
                        }
                    }
                    catch (Exception e)
                    {
                        fs.Flush();
                        throw new FailedSendingException($"Failed while sending '{file.Name}' ({e.Message}).");
                    }


                    bytesToSend -= bufferSize;
                    bytesSent   += bufferSize;


                    if (bytesSent >= report.CurrentBytes + (totalBytes / 100) || bytesToSend == 0)
                    {
                        report.CurrentBytes = bytesSent;
                        transferProgress.Report(report);
                    }
                }
                fs.Flush();
            }
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            _Token = _TokenSource.Token;

            Task.Run(() => StartEchoServer(), _Token);

            _Client = new CavemanTcpClient("127.0.0.1", 9000, false, null, null);
            _Client.Events.ClientConnected += (s, e) =>
            {
                Console.WriteLine("[Client] connected");
            };

            _Client.Events.ClientDisconnected += (s, e) =>
            {
                Console.WriteLine("[Client] disconnected");
            };

            _Client.Logger = Console.WriteLine;

            while (_RunForever)
            {
                Console.Write("Command [? for help]: ");
                string userInput = Console.ReadLine();
                if (String.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                switch (userInput)
                {
                case "?":
                    Console.WriteLine("Available commands:");
                    Console.WriteLine("q         quit");
                    Console.WriteLine("cls       clear the screen");
                    Console.WriteLine("connect   connect to server");
                    Console.WriteLine("send      send clientecho to the server");
                    Console.WriteLine("read      read data from the server");
                    Console.WriteLine("");
                    break;

                case "q":
                    _RunForever = false;
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "connect":
                    _Client.Connect(5000);
                    break;

                case "send":
                    _Client.Send("clientecho");
                    break;

                case "read":
                    ReadResult rr = _Client.Read(10);
                    if (rr.Status == ReadResultStatus.Success)
                    {
                        Console.WriteLine("[Client] read 10 bytes: " + Encoding.UTF8.GetString(rr.Data));
                    }
                    else
                    {
                        Console.WriteLine("*** [Client] read status: " + rr.Status.ToString());
                    }
                    break;
                }
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            InitializeClient();
            Console.WriteLine("Connecting to ssl://127.0.0.1:8000");
            _Client.Connect(10);

            while (_RunForever)
            {
                Console.Write("Command [? for help]: ");
                string userInput = Console.ReadLine();
                if (String.IsNullOrEmpty(userInput))
                {
                    continue;
                }

                if (userInput.Equals("?"))
                {
                    Console.WriteLine("-- Available Commands --");
                    Console.WriteLine("");
                    Console.WriteLine("   cls                  Clear the screen");
                    Console.WriteLine("   q                    Quit the program");
                    Console.WriteLine("   send [data]          Send data to the server");
                    Console.WriteLine("   sendt [ms] [data]    Send data to the server with specified timeout");
                    Console.WriteLine("   read [count]         Read [count] bytes from the server");
                    Console.WriteLine("   readt [ms] [count]   Read [count] bytes from the server with specified timeout");
                    Console.WriteLine("   dispose              Dispose of the client");
                    Console.WriteLine("   start                Start the client (connected: " + (_Client != null ? _Client.IsConnected.ToString() : "false") + ")");
                    Console.WriteLine("   stats                Retrieve statistics");
                    Console.WriteLine("");
                    continue;
                }

                if (userInput.Equals("c") || userInput.Equals("cls"))
                {
                    Console.Clear();
                    continue;
                }

                if (userInput.Equals("q"))
                {
                    _RunForever = false;
                    break;
                }

                if (userInput.StartsWith("send "))
                {
                    string[] parts = userInput.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string   data  = parts[1];

                    WriteResult wr = _Client.Send(data);
                    if (wr.Status == WriteResultStatus.Success)
                    {
                        Console.WriteLine("Success");
                    }
                    else
                    {
                        Console.WriteLine("Non-success status: " + wr.Status);
                    }
                }

                if (userInput.StartsWith("sendt "))
                {
                    string[] parts     = userInput.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
                    int      timeoutMs = Convert.ToInt32(parts[1]);
                    string   data      = parts[2];

                    WriteResult wr = _Client.SendWithTimeout(timeoutMs, data);
                    if (wr.Status == WriteResultStatus.Success)
                    {
                        Console.WriteLine("Success");
                    }
                    else
                    {
                        Console.WriteLine("Non-success status: " + wr.Status);
                    }
                }

                if (userInput.StartsWith("read "))
                {
                    string[] parts = userInput.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    int      count = Convert.ToInt32(parts[1]);

                    ReadResult rr = _Client.Read(count);
                    if (rr.Status == ReadResultStatus.Success)
                    {
                        Console.WriteLine("Retrieved " + rr.BytesRead + " bytes: " + Encoding.UTF8.GetString(rr.Data));
                    }
                    else
                    {
                        Console.WriteLine("Non-success status: " + rr.Status.ToString());
                    }
                }

                if (userInput.StartsWith("readt "))
                {
                    string[] parts     = userInput.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
                    int      timeoutMs = Convert.ToInt32(parts[1]);
                    int      count     = Convert.ToInt32(parts[2]);

                    ReadResult rr = _Client.ReadWithTimeout(timeoutMs, count);
                    if (rr.Status == ReadResultStatus.Success)
                    {
                        Console.WriteLine("Retrieved " + rr.BytesRead + " bytes: " + Encoding.UTF8.GetString(rr.Data));
                    }
                    else
                    {
                        Console.WriteLine("Non-success status: " + rr.Status.ToString());
                    }
                }

                if (userInput.Equals("dispose"))
                {
                    _Client.Dispose();
                }

                if (userInput.Equals("start"))
                {
                    InitializeClient();
                    _Client.Connect(10);
                }

                if (userInput.Equals("stats"))
                {
                    Console.WriteLine(_Client.Statistics);
                }
            }
        }