Пример #1
0
 void ReadThread()
 {
     ServerStarted?.Invoke();
     while (!_stop)
     {
         try
         {
             var data         = _udpClient.Receive(ref _remoteIPEndPoint);
             var loggingEvent = Encoding.UTF8.GetString(data);
             if (LogReceived != null)
             {
                 Task.Factory.StartNew(() =>
                 {
                     try
                     {
                         LogReceived(loggingEvent);
                     }
                     catch (Exception ex)
                     {
                     }
                 });
             }
         }
         catch (Exception ex)
         {
         }
     }
     ServerStoped?.Invoke();
 }
Пример #2
0
        public bool Initialize(int port)
        {
            try
            {
                var config = new NetPeerConfiguration("Mafia")
                {
                    Port = port
                };
                _server = new NetServer(config);
                _server.Start();
                if (_server.Status != NetPeerStatus.Running)
                {
                    return(false);
                }
                IsCancelled = false;
                Debug.WriteLine("Server has started");
                RunListener();
                Debug.WriteLine("Server is listening");
                Status = "Server is listening for connections";
                if (ServerStarted != null)
                {
                    ServerStarted.Invoke(null, null);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                Status = ex.ToString();
            }

            return(false);
        }
Пример #3
0
        /// <summary>
        /// Server startup method.
        /// </summary>
        /// <param name="port"></param>
        /// <param name="backlog"></param>
        /// <returns></returns>
        public async Task <CoreServerBase> StartAsync(int port, int backlog = 10)
        {
            if (port <= 0 || IsServerListerning)
            {
                return(this);
            }

            ServerPort = port;
            try {
                await ServerSemaphore.WaitAsync().ConfigureAwait(false);

                Logger.Log("Starting TCP Server...");
                Server = new TcpListener(new IPEndPoint(IPAddress.Any, ServerPort));
                Server.Start(backlog);

                Logger.Log($"Server waiting for connections at port -> {ServerPort}");

                Helpers.InBackgroundThread(async() => {
                    try {
                        await ServerListerningSemaphore.WaitAsync().ConfigureAwait(false);

                        while (!ExitRequested && Server != null)
                        {
                            IsServerListerning = true;

                            if (!_isListernerEventFired)
                            {
                                ServerStarted?.Invoke(this, new OnServerStartedListerningEventArgs(IPAddress.Any, ServerPort, DateTime.Now));
                                _isListernerEventFired = true;
                            }

                            if (Server.Pending())
                            {
                                TcpClient client            = await Server.AcceptTcpClientAsync().ConfigureAwait(false);
                                Connection clientConnection = new Connection(client, this);
                                ClientConnected?.Invoke(this, new OnClientConnectedEventArgs(clientConnection.ClientIpAddress, DateTime.Now, clientConnection.ClientUniqueId));
                                await clientConnection.Init().ConfigureAwait(false);
                            }

                            await Task.Delay(1).ConfigureAwait(false);
                        }

                        IsServerListerning = false;
                    }
                    finally {
                        ServerListerningSemaphore.Release();
                    }
                }, GetHashCode().ToString(), true);

                while (!IsServerListerning)
                {
                    await Task.Delay(1).ConfigureAwait(false);
                }

                return(this);
            }
            finally {
                ServerSemaphore.Release();
            }
        }
Пример #4
0
        void listenerSocket_IsListeningChanged(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if ((socket.IsListening) && (ServerStarted != null))
            {
                ServerStarted.Invoke(this, new EventArgs());
            }
        }
Пример #5
0
        private void OnServerStarted(ServerStarted ev)
        {
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                _mainModel.StatusBar.CurrentStatus = "Running.";
                _mainModel.Info.StartUptimeCounter();

            }));
        }
Пример #6
0
 public void Start()
 {
     main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     main.Bind(new IPEndPoint(address, port));
     main.Listen(acceptQueueLength);
     StartAccept();
     StartReceive();
     ServerStarted?.Invoke(this, new GameEventArgs(null, string.Empty));
 }
Пример #7
0
    public override void OnStartServer()
    {
        //Base handling
        base.OnStartServer();
        //Reset the network scene name
        networkSceneName = string.Empty;

        //Fire event
        if (ServerStarted != null)
        {
            ServerStarted.Invoke();
        }
    }
Пример #8
0
        private void OnServerStarted()
        {
            if (ServerStarted == null)
            {
                return;
            }

            Task.Run(() =>
            {
                ServerStarted?.Invoke(this, new InternetEventArgs {
                    Local = this
                });
            });
        }
Пример #9
0
 /// <summary>
 /// Starts the server
 /// </summary>
 public void Start()
 {
     IsRunning = true;
     try
     {
         hl.Start();
         ServerStarted?.Invoke();
         hl.BeginGetContext(new AsyncCallback(ServerProc), hl);
     }
     catch (HttpListenerException ex)
     {
         ExceptionOccured?.Invoke(ex);
     }
 }
Пример #10
0
        /// <summary>
        /// Start server and listen to incoming connection from defined TCP Port.
        /// </summary>
        /// <param name="port">TCP Port to listen for incoming connection.</param>
        /// <exception cref="ArgumentOutOfRangeException">Port number is beyond the range of [0 - 65535] </exception>
        /// <remarks>
        /// Calling this function has no effect once server is started.
        /// </remarks>
        public void Start(int port)
        {
            if (ConnectionMonitoring != null)
            {
                return;
            }
            Port     = port;
            listener = new TcpListener(IPAddress.Any, Port);

            Abort = false;
            ConnectionMonitoring      = new Thread(MonitorIncomingConnection);
            ConnectionMonitoring.Name = "Connection Monitoring";
            ConnectionMonitoring.Start();
            ServerStarted?.Invoke(this, null);
            Trace.WriteLine(Name + ":TCP Server Started at port " + Port);
        }
Пример #11
0
        private void ServerWork()
        {
            IsRunning = true;
            ServerStarted?.Invoke(this, EventArgs.Empty);

            try
            {
                _server = new Server(Behaviour);
                _server.Run();
            }
            catch (Exception)
            {
            }

            IsRunning = false;
        }
        private void RaiseServerChangedEvent(MediaControllerNativeServerState state, MediaController controller)
        {
            if (controller == null)
            {
                return;
            }

            if (state == MediaControllerNativeServerState.Activated)
            {
                ServerStarted?.Invoke(this, new MediaControlServerStartedEventArgs(controller));
            }
            else
            {
                controller.RaiseStoppedEvent();
                ServerStopped?.Invoke(this, new MediaControlServerStoppedEventArgs(controller.ServerAppId));
            }
        }
Пример #13
0
        //Dedicate one thread to incoming connections
        private void ThreadListener()
        {
            try
            {
                ServerStarted?.Invoke();

                while (true)
                {
                    Socket hNewConnection = m_hListener.Accept(); //il thread sta in attesa per una connessione in ingresso

                    //T deve ricevere il socket, 2 modi: 1) T implementa un interfaccia interna, 2) creiamo un allocatore per T
                    T hConnHandler = new T();
                    hConnHandler.Socket = hNewConnection;
                    hConnHandler.CreateBuffer(m_iBufferSize);

                    lock (m_hConnections)
                    {
                        hConnHandler.Id    = s_iCounter;
                        hConnHandler.Owner = this;

                        m_hConnections.Add(hConnHandler.Id, hConnHandler);
                        s_iCounter++;                        
                    }

                    hConnHandler.BeginReceive(); //connection now active, let the user code handle requests and resposes

                    try
                    {
                        ClientConnected?.Invoke(hConnHandler);
                    }
                    catch (Exception)
                    {
                        //Se qualcuno nell'implementazione dell'evento fa danni... a noi non ci interessa
                    }
                }
            }
            catch (Exception)
            {
                //se siamo qui è xche abbiamo chiamato stop quindi possiamo interrompere il ciclo
                ServerStopped?.Invoke();                
            }
        }
Пример #14
0
        public void Start()
        {
            if (IsRunning)
            {
                return;
            }

            CancellationTokenSource = new CancellationTokenSource();

            Logger.Instance.Log(LogLevel.Message, "Starting the HttpListener server...");

            Listener.Start();

            Logger.Instance.Log(LogLevel.Message, "Server started.");

            Task.Factory.StartNew(ReceiveRequests, CancellationTokenSource.Token);

            IsRunning = true;
            ServerStarted?.Invoke(this, EventArgs.Empty);
        }
Пример #15
0
        private void InitializeServer(HostTopology topology)
        {
            if (m_Settings.m_SimulateNetworking)
            {
                m_HostID = NetworkTransport.AddHostWithSimulator(topology, m_Settings.m_MinLatency, m_Settings.m_MaxLatency, m_Settings.m_Port);
            }
            else
            {
                m_HostID = NetworkTransport.AddHost(topology, m_Settings.m_Port);
            }

            IsConnected = true;
            IsServer    = true;

            ServerStarted?.Invoke();

            RegisterHandlers();
            LoadOnlineScene();

            DebugLog("Server started...");
        }
Пример #16
0
        /// <summary>
        /// 开始监听
        /// </summary>
        public Task RunAsync(CancellationToken cancellationToken)
        {
            connectionCount   = 0;
            sendBytesCount    = 0;
            receiveBytesCount = 0;

            startTime = DateTime.Now;
            stopTime  = default(DateTime);

            listen = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay           = true,
                ReceiveBufferSize = options.Value.ReceiveBufferSize,
                SendBufferSize    = options.Value.SendBufferSize,
                SendTimeout       = options.Value.SendTimeOut * 1000,
            };

            foreach (var item in options.Value.Listeners)
            {
                var local = new IPEndPoint(IPAddress.Parse(item.Ip), item.Post);
                listen.Bind(local);
            }

            listen.Listen(options.Value.ListenBacklog);

            isRun = 1;
            ServerStarted?.Invoke(this, new EventArgs());
            OnServerStarted();
            startAccept();

            var asyncTaskMethodBuilder = AsyncTaskMethodBuilder.Create();

            cancellationToken.Register(new Action(() =>
            {
                this.Stop();
                asyncTaskMethodBuilder.SetResult();
            }));
            return(asyncTaskMethodBuilder.Task);
        }
Пример #17
0
        /// <summary>
        /// 开始监听
        /// </summary>
        public async Task RunAsync(CancellationToken cancellationToken)
        {
            connectionCount   = 0;
            sendBytesCount    = 0;
            receiveBytesCount = 0;

            startTime = DateTime.Now;
            stopTime  = default(DateTime);

            var option = options.Value;

            var bossGroup   = new MultithreadEventLoopGroup(option.ParentGroupCount);
            var workerGroup = new MultithreadEventLoopGroup(option.ChildGroupCount);
            var bootstrap   = new ServerBootstrap();

            bootstrap
            .Group(bossGroup, workerGroup)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, option.ListenBacklog)
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new ArrayToByteEncoder(), new ArraySegmentToByteEnCoder(), new EnCoder(EnCodeRequestInfo));
                pipeline.AddLast(new DeCoder(DeCodeRequestInfo), new SessionHandler(ChannelActive, ChannelInactive, ChannelRead));
            }));

            foreach (var item in option.Listeners.Split(new char[] { ';' }))
            {
                var arr = item.Split(new char[] { ':' });
                var bootstrapChannel = await bootstrap.BindAsync(IPAddress.Parse(arr[0]), int.Parse(arr[1]));

                this.channels.Add(bootstrapChannel);
            }

            isRun = 1;
            ServerStarted?.Invoke(this, new EventArgs());
            OnServerStarted();
        }
Пример #18
0
        public void Start(bool waitForUserTypeExit = true)
        {
            if (Started)
            {
                throw new Exception("Server already has been started.");
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Initialize();
            ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));

            ServerSocket.Listen(0);
            ServerSocket.BeginAccept(AcceptCallback, null);
            Started = true;
            ServerStarted?.Invoke();
            RunServerStartupTasks();
            sw.Stop();
            LogController.WriteLog(new ServerLog($"Server started in {sw.ElapsedMilliseconds}ms", "Server", "Start"));
            LogController.WriteLog(new ServerLog($"Running at port {Port}"));
            Console.WriteLine("Type 'exit' to stop; 'reboot' to send reboot request event...");
            string line = "";

            if (waitForUserTypeExit)
            {
                while (line != "exit")
                {
                    line = Console.ReadLine();
                    if (line == "reboot")
                    {
                        RebootRequest?.Invoke();
                    }
                }
            }
        }
Пример #19
0
 private void OnStartServer(bool embedded)
 {
     IsEmbedded = embedded;
     ServerStarted?.Invoke(serverProcess, new ServerStartEventArgs(embedded));
 }
Пример #20
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            Thread.Sleep(2000);
            AppDomain.CurrentDomain.UnhandledException += (o, a) =>
            {
                System.Diagnostics.Process.Start("ShiftOS.Server.exe");
                Environment.Exit(0);
            };
            UserConfig.Get();
            System.Timers.Timer tmr = new System.Timers.Timer(5000);
            tmr.Elapsed += (o, a) =>
            {
                if (server.IsOnline)
                {
                    try
                    {
                        server.DispatchAll(new NetObject("heartbeat", new ServerMessage
                        {
                            Name = "heartbeat",
                            GUID = "server"
                        }));
                    }
                    catch { }
                }
            };
            if (!Directory.Exists("saves"))
            {
                Directory.CreateDirectory("saves");
            }

            if (!Directory.Exists("scripts"))
            {
                Console.WriteLine("Creating scripts directory...");
                Directory.CreateDirectory("scripts");
                Console.WriteLine("NOTE: This MUD is not just gonna generate scripts for you. You're going to need to write them. YOU are DevX.");
            }

            Console.WriteLine("Starting server...");
            server = new NetObjectServer();

            server.OnStarted += (o, a) =>
            {
                Console.WriteLine($"Server started on address {server.Address}, port {server.Port}.");
                ServerStarted?.Invoke(server.Address.ToString());
                tmr.Start();
            };

            server.OnStopped += (o, a) =>
            {
                Console.WriteLine("WARNING! Server stopped.");
                tmr.Stop();
            };

            server.OnError += (o, a) =>
            {
                Console.WriteLine("ERROR: " + a.Exception.Message);
            };

            server.OnClientAccepted += (o, a) =>
            {
                Console.WriteLine("Client connected.");
                try
                {
                    server.DispatchTo(a.Guid, new NetObject("welcome", new ServerMessage {
                        Name = "Welcome", Contents = a.Guid.ToString(), GUID = "Server"
                    }));
                }
                catch
                {
                    Console.WriteLine("Oh, you don't have time to finish the handshake? Fine. Get off.");
                }
            };

            server.OnClientDisconnected += (o, a) =>
            {
                Console.WriteLine("Client disconnected.");
            };

            server.OnClientRejected += (o, a) =>
            {
                Console.WriteLine("F**K. Something HORRIBLE JUST HAPPENED.");
            };


            server.OnReceived += (o, a) =>
            {
                var obj = a.Data.Object;

                var msg = obj as ServerMessage;

                if (msg != null)
                {
                    Interpret(msg);
                }
            };

            IPAddress defaultAddress = null;

            var host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    defaultAddress = ip;
                }
            }

            try
            {
                server.Start(defaultAddress, 13370);
            }
            catch
            {
                Console.WriteLine("So we tried to bind the server to your IP address automatically, but your operating system or the .NET environment you are in (possibly Mono on Linux) is preventing us from doing so. We'll try to bind to the loopback IP address (127.0.0.1) and if that doesn't work, the multi-user domain software may not be compatible with this OS or .NET environment.");
                server.Stop();
                server.Start(IPAddress.Loopback, 13370);
            }
            ClientDispatcher  = new Server.MudClientDispatcher(server);
            server.OnStopped += (o, a) =>
            {
                Console.WriteLine("Server stopping.");
            };

            /*
             * var task = ChatBackend.StartDiscordBots();
             * task.Wait();
             */


            while (server.IsOnline)
            {
                Console.Write("> ");
                string cmd = Console.ReadLine();
                try
                {
                    if (cmd.ToLower().StartsWith("decrypt "))
                    {
                        string username = cmd.Remove(0, 8);
                        if (File.Exists("saves/" + username + ".save"))
                        {
                            Console.WriteLine(ReadEncFile("saves/" + username + ".save"));
                        }
                        else
                        {
                            Console.WriteLine("Save not found.");
                        }
                    }
                    else if (cmd == "purge_all_bad_saves")
                    {
                        foreach (var f in Directory.GetFiles("saves"))
                        {
                            try
                            {
                                Console.WriteLine("Testing " + f + "...");
                                ReadEncFile(f);
                                Console.WriteLine("OK");
                            }
                            catch
                            {
                                Console.WriteLine("Not OK. Deleting.");
                                File.Delete(f);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Пример #21
0
 protected virtual void OnServerConnected()
 {
     ServerStarted?.Invoke(this, EventArgs.Empty);
 }
Пример #22
0
 internal void HandleServerStarted(object sender, EventArgs args)
 {
     WrappedEventHandler(() => ServerStarted?.Invoke(sender, args), "ServerStarted", sender);
 }
Пример #23
0
 internal static void InvokeServerStarted()
 {
     ServerStarted?.Invoke();
 }
Пример #24
0
 internal void HandleServerStarted(object sender, EventArgs args)
 {
     ServerStarted?.Invoke(sender, args);
 }
Пример #25
0
 protected virtual void OnServerStarted(EventArgs e) => ServerStarted?.Invoke(this, e);
 private void OnServerStarted() => ServerStarted?.Invoke();
Пример #27
0
        // This event will be raised once the output parser sees this line:
        // [14:57:57] [Server thread/INFO]: Done (2,631s)! For help, type "help" or "?"

        protected void OnServerStarted()
        {
            ServerStarted?.Invoke(mvarID);
        }
Пример #28
0
        /// <summary>
        /// Open port start listening for connections
        /// </summary>
        /// <exception cref="Exception">Thown if server does not startup correctly</exception>
        public void ServerStart()
        {
            if (IsRunning)
            {
                return;
            }
            _startError = false;

            //start up the thread if needed
            if (_thrSend == null || _thrSend.ThreadState == ThreadState.Aborted)
            {
                _thrSend = new Thread(new ThreadStart(SendLoop));
                _thrSend.IsBackground = true;
            }
            if (!_thrSend.IsAlive)
            {
                _thrSend.Start();
            }

            //verify that connection is disposed and then recreate it
            if (_listenSock != null)
            {
                _listenSock.Dispose();
            }
            _listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                _listenSock.Bind(new IPEndPoint(IPAddress.Any, _portNumber));
            }
            catch (Exception ex)
            {
                Console.WriteLine("ServerStart:bind " + ex.ToString());
                _startError = true;
            }

            try
            {
                _listenSock.Listen(_maxConnections);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ServerStart:Listen " + ex.ToString());
                _startError = true;
            }

            try
            {
                _listenSock.BeginAccept(cbAcceptDone, _listenSock);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ServerStart:BeginAccept " + ex.ToString());
                _startError = true;
            }

            if (!_startError)
            {
                try
                {
                    //dispatch call into the proper thread
                    _context.Post(s =>
                    {
                        ServerStarted?.Invoke();
                    }, null);
                    //ServerStarted?.Invoke();
                }
                catch (Exception ex)
                {
                    //dont trust user code
                    Console.WriteLine("Calling server ServerStarted event handler threw an exception");
                }
            }
            else
            {
                throw new Exception("Unable to start server");
            }
        }
Пример #29
0
 public void ServerStart()
 {
     ServerStarted.Add(Now);
 }
Пример #30
0
        public static void Main(string[] args)
        {
            if (!Directory.Exists("saves"))
            {
                Directory.CreateDirectory("saves");
            }

            if (!File.Exists("chats.json"))
            {
                SaveChats();
            }
            else
            {
                LoadChats();
            }

            if (!Directory.Exists("scripts"))
            {
                Console.WriteLine("Creating scripts directory...");
                Directory.CreateDirectory("scripts");
                Console.WriteLine("NOTE: This MUD is not just gonna generate scripts for you. You're going to need to write them. YOU are DevX.");
            }

            Console.WriteLine("Starting server...");
            server = new NetObjectServer();

            server.OnStarted += (o, a) =>
            {
                Console.WriteLine($"Server started on address {server.Address}, port {server.Port}.");
                ServerStarted?.Invoke(server.Address.MapToIPv4().ToString());
            };

            server.OnStopped += (o, a) =>
            {
                Console.WriteLine("WARNING! Server stopped.");
            };

            server.OnError += (o, a) =>
            {
                Console.WriteLine("ERROR: " + a.Exception.Message);
            };

            server.OnClientAccepted += (o, a) =>
            {
                Console.WriteLine("Client connected.");
                server.DispatchTo(a.Guid, new NetObject("welcome", new ServerMessage {
                    Name = "Welcome", Contents = a.Guid.ToString(), GUID = "Server"
                }));
            };

            server.OnReceived += (o, a) =>
            {
                var obj = a.Data.Object;

                var msg = obj as ServerMessage;

                if (msg != null)
                {
                    Interpret(msg);
                }
            };

            IPAddress defaultAddress = null;

            var host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    defaultAddress = ip;
                }
            }

            try
            {
                server.Start(defaultAddress, 13370);
            }
            catch
            {
                Console.WriteLine("So we tried to bind the server to your IP address automatically, but your operating system or the .NET environment you are in (possibly Mono on Linux) is preventing us from doing so. We'll try to bind to the loopback IP address (127.0.0.1) and if that doesn't work, the multi-user domain software may not be compatible with this OS or .NET environment.");
                server.Stop();
                server.Start(IPAddress.Loopback, 13370);
            }

            var hConf = new HostConfiguration();

            hConf.UrlReservations.CreateAutomatically = true;

            var nancy = new NancyHost(hConf, new Uri("http://localhost:13371/"));

            server.OnStopped += (o, a) =>
            {
                nancy.Stop();
            };

            nancy.Start();
        }
Пример #31
0
        private void Listen()
        {
            IPAddress adress = IPAddress.Parse(_mainHost);

            using (_mainSocket = new Socket(adress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                _mainSocket.Bind(new IPEndPoint(adress, _mainPort));
                _mainSocket.Listen(100);
                _isWork = true;
                ServerStarted?.Invoke();
                ConnectionsChange?.Invoke(clients.Count);
                while (!_tryStop)
                {
                    Socket clientSocket = _mainSocket.Accept();
                    lock (clients)
                    {
                        clients.Add(new ServerClient(clientSocket,
                                                     (disconnectedClient) =>
                        {
                            lock (clients)
                            {
                                if (clients.Contains(disconnectedClient) && !_tryStop)
                                {
                                    clients.Remove(disconnectedClient);
                                    if (disconnectedClient.UserName != "")
                                    {
                                        ClientLogoutEvent?.Invoke(disconnectedClient.UserName);
                                    }
                                }
                                ConnectionsChange?.Invoke(clients.Count);
                            }
                        },
                                                     (header, sendedToAllData) =>
                        {
                            lock (clients)
                            {
                                foreach (ServerClient client in clients)
                                {
                                    client.SendData(header, sendedToAllData);
                                }
                            }
                        },
                                                     (header, sendToUserData, userName) =>
                        {
                            lock (clients)
                            {
                                clients.FirstOrDefault(c => c.UserName == userName)?.SendData(header, sendToUserData);
                            }
                        },
                                                     (userName) =>
                        {
                            lock (clients)
                            {
                                if (clients.FirstOrDefault(c => c.UserName == userName) == null)
                                {
                                    ClientLoginEvent?.Invoke(userName);
                                    return(true);
                                }
                            }
                            return(false);
                        }));

                        ConnectionsChange?.Invoke(clients.Count);
                    }
                }
                lock (clients)
                {
                    foreach (ServerClient c in clients)
                    {
                        c.Disconnect();
                    }
                    clients.Clear();
                }
                //_mainSocket.Shutdown(SocketShutdown.Both);
                _mainSocket.Close();
                _isWork = false;
                ServerStopped?.Invoke();
            }
        }