public void Dispose() { var users = ChatLogic.GetAllUsers(); var tcpClients = _tcpClients.Union(users.Select(x => x.TcpClient)).ToList(); foreach (var tcpClient in tcpClients) { DisconnectTcpClient(tcpClient); } StopTcpServer(); }
// Асинхронное обслуживание конкретного подключения private void ConnectionServiceAsync(TcpClient tcpClient) { Task.Run(() => { var user = ConnectTcpClient(tcpClient); if (user == null) { DisconnectTcpClient(tcpClient); return; } ChatLogic.ReceiveMessagesFromUser(user); DisconnectUser(user); }); }
// Обработка подключенного пользователя и отправка ему всей нужной информации private bool ConnectUser(UserModel user) { var ok = string.Concat(ChatConstants.Separator, ChatConstants.Ok, ChatConstants.Separator); var isConnected = ChatLogic.SendMessageToUser(user, ok); if (isConnected) { var users = ChatLogic.GetAllUsers(); string usernames = null; if (users.Count == 0) { usernames = string.Concat(ChatConstants.Separator, ChatConstants.Server, ChatConstants.Separator); } else { usernames = string.Join(ChatConstants.Separator, users.Select(x => x.Username)); } isConnected = ChatLogic.SendMessageToUser(user, usernames); } if (isConnected) { var commands = string.Empty; foreach (ChatCommands command in Enum.GetValues(typeof(ChatCommands))) { commands += string.Concat(ChatConstants.Separator, command.ToName()); } isConnected = ChatLogic.SendMessageToUser(user, commands); } if (isConnected) { _tcpClients.Remove(user.TcpClient); ChatLogic.AddUser(user); ChatLogic.UserStateChanged(user.Username, true); } return(isConnected); }
// Отключение пользователя private void DisconnectUser(UserModel user) { ChatLogic.RemoveUser(user); ChatLogic.UserStateChanged(user.Username, false); DisconnectTcpClient(user.TcpClient); }