protected virtual void OnClientLogout(string cName, Socket socket) { ClientLogoutEvent?.Invoke(this, new ClientEventArgs() { clientName = cName, clientSocket = socket }); }
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(); } }