Beispiel #1
0
        private static async Task RunServer(int port)
        {
            await using var server = new TcpServer(IPAddress.Any, port);
            await server.StartAsync();

            Console.WriteLine("Ending");
        }
        /// <summary>
        /// Основная программа приложения сервера
        /// для выхода ввести "y" или "Y"
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static async Task Main(string[] args)
        {
            CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
            CancellationToken       token             = cancelTokenSource.Token;

            var server = new TcpServer(IPAddress.Any, port);

            server.OnDataReceived += (sender, e) =>
            {
                byte[] buffer    = new byte[bufferSize];
                int    bytesRead = 0;
                string message   = string.Empty;
                do
                {
                    bytesRead = e.Stream.Read(buffer, 0, bufferSize);
                    message  += Encoding.UTF8.GetString(buffer, 0, bytesRead);
                }while (bytesRead > 0 && e.Stream.DataAvailable);

                var serverMessage = new ServerMessage
                {
                    Date = e.Date,
                    Text = message,
                    Ip   = e.Ip
                };
                // Сохранить полученное сообщение в БД
                SaveMessage(serverMessage);
            };
            var    serverTask    = server.StartAsync();
            string messageString = string.Empty;

            while (messageString.ToUpper() != stopCommand)
            {
                Console.WriteLine("Enter command: ");
                messageString = Console.ReadLine();
                if (messageString.ToUpper() == stopCommand)
                {
                    server.Stop();
                }
                else if (messageString == printCommand)
                {
                    PrintResults();
                }
            }
            await serverTask;
        }
Beispiel #3
0
        public void Start(int port)
        {
            using (var server = new TcpServer(IPAddress.Any, port))
            {
                server.OnDataReceived += async(sender, stream) =>
                {
                    BinaryReader  reader  = new BinaryReader(stream);
                    RequestOpcode request = (RequestOpcode)reader.ReadByte();
                    byte[]        guidBytes;
                    Guid          id;

                    switch (request)
                    {
                    case RequestOpcode.JobRequest:
                        guidBytes = reader.ReadBytes(16);
                        id        = new Guid(guidBytes);

                        BinaryWriter writer = new BinaryWriter(stream);

                        if (finished ||
                            prefixes.All(x => x.Value != null &&
                                         DateTime.Now - x.Value.LastActivity < timeout))
                        {
                            Console.WriteLine($"No more jobs for {id}");
                            writer.Write(0);
                            return;
                        }

                        var prefix = prefixes.First(x => x.Value == null ||
                                                    DateTime.Now - x.Value.LastActivity >= timeout).Key;
                        prefixes[prefix] = new AssociatedClient(id, DateTime.Now);

                        if (prefix == "")
                        {
                            writer.Write(-PerClientLength);
                        }
                        else
                        {
                            writer.Write(PerClientLength);
                        }

                        writer.Write(prefix);
                        writer.Write(desiredHash.Length);
                        writer.Write(desiredHash);

                        Console.WriteLine($"Client {id} connected, given job \"{prefix}\"");

                        break;

                    case RequestOpcode.HashNotFound:
                        guidBytes = reader.ReadBytes(16);
                        id        = new Guid(guidBytes);

                        Console.WriteLine($"Client {id} finished, hash not found");

                        if (prefixes.Any(p => p.Value != null && p.Value.guid == id))
                        {
                            var    tmp       = prefixes.FirstOrDefault(p => p.Value.guid == id);
                            string hisPrefix = tmp.Key;
                            prefixes.Remove(hisPrefix);

                            if (prefixes.Count == 0)
                            {
                                Console.WriteLine("All prefixes checked, no result found");
                                finished = true;
                                await Task.Delay(timeout);

                                server.Stop();
                            }
                        }
                        break;

                    case RequestOpcode.HashFound:
                        string result = reader.ReadString();
                        Console.WriteLine($"Result found, string: {result}");
                        Console.WriteLine("Waiting for all the clients to finish");
                        finished = true;

                        await Task.Delay(timeout);

                        while (prefixes.Any(x => x.Value != null &&
                                            DateTime.Now - x.Value.LastActivity < timeout))
                        {
                            await Task.Delay(1000);

                            Console.WriteLine("Waiting..");
                        }

                        server.Stop();
                        Console.WriteLine("Stopping..");
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                };

                Task serverTask = server.StartAsync();
                Console.WriteLine("Server started, listening to incoming connections");
                serverTask.Wait();
                Console.WriteLine("Server stopped");
            }
        }