Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Server = new TcpServer();
            Server.Start(8888);
            Server.Connected += Server_Connected;

            Console.ReadKey();

            Server.Stop();
        }
Ejemplo n.º 2
0
        /// <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;
        }
Ejemplo n.º 3
0
 private void ServerForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     FSServidor.Stop();
     FRServidor.Stop();
 }
Ejemplo n.º 4
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");
            }
        }