Exemplo n.º 1
0
        private async Task ProcessClientAsync(TcpClient client)
        {
            try
            {
                ConnectionPool.Add(client);

                var cts = new CancellationTokenSource();
                cts.CancelAfter((int)ReadTimeOut.TotalMilliseconds);
                var token = cts.Token;

                //var buffer = new byte[256];
                //client.GetStream().Read(buffer, 0, buffer.Length);
                //return;

                var connection = new ClientConnection(client);

                var caption = await connection.ReadStringAsync(token);

                if (caption != MessageCaption)
                {
                    Console.WriteLine("Wrong request");
                    return;
                }


                var commandCode = (CommandCodeEn)await connection.ReadByteAsync(token);

                if (commandCode == CommandCodeEn.Ping)
                {
                    var handler = new PingCommandHandler();
                    await handler.ProcessRequestAsync(client, token);
                }
                else if (commandCode == CommandCodeEn.GetDate)
                {
                    var handler = new GetDateCommandHandler();
                    await handler.ProcessRequestAsync(client, token);
                }
                else if (commandCode == CommandCodeEn.PutFile)
                {
                    var handler = new SaveFileCommandHandler();
                    await handler.ProcessRequestAsync(client, token);
                }
                else
                {
                    throw new Exception($"Invalid command code: {commandCode}");
                }

                var taken = ConnectionPool.TryTake(out client);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }