internal void Disconnect(string message) { this.Asyn = null; Stream.Flush(); IsDisconnect = true; DisconnectDateTime = DateTime.Now; if (AsyncCallDict != null) { AsyncCallDict.Clear(); } if (CallBackDict != null) { foreach (var item in CallBackDict.Values) { var disconn = GetExceptionResult("Disconnect", (int)ErrorTag.Disconnect, item.Id); disconn.Arguments = new List <byte[]>(); item.SetRes(disconn); } CallBackDict.Clear(); } UserDisconnect?.Invoke(this, message); UserDisconnect = null; }
void Listen_server(object socket) { Socket connectionSocket = socket as Socket; while (true) { try { object serverMessage; { byte[] serverData = new byte[10000]; if (connectionSocket.Receive(serverData) == 0) { Console.WriteLine("00000000"); return; } serverMessage = Functions.Deserialize(serverData); Console.WriteLine("Получен ответ"); } if (serverMessage is MessageFromServer) { MessageFromServer message = (serverMessage as MessageFromServer); if (message.Message.IndexOf("Пользователь") != -1) { Dispatcher.Invoke(() => { if (!OnlineAndAllCheckBox.IsChecked.Value) { _getUsersOnline.BeginInvoke(null, null); } }); } else { MessageBox.Show(message.Message); } Console.WriteLine("Пришло простое сообщение от сервера"); } if (serverMessage is GetUsersOnline) { GetUsersOnline usersInform = serverMessage as GetUsersOnline; Console.WriteLine("Пришёл список пользователей"); Dispatcher.Invoke(() => { if (OnlineAndAllCheckBox.IsChecked.Value) { return; } UsersListBox.Items.Clear(); foreach (AccountInformation t in usersInform.AccountsInformation) { UsersListBox.Items.Add(new Correspondence(t)); } }); } if (serverMessage is GetMessages) { Console.WriteLine("Пришла переписка с пользователем"); Dispatcher.Invoke(() => { listMessagesStackPanel.Children.Clear(); foreach (Message message in (serverMessage as GetMessages).Messages) { DrawingMessage(message); message.WhetherRead = true; Functions.SerializeAndSend(message, _connectionSocket); } }); } if (serverMessage is Message) { Message message = (serverMessage as Message); Console.WriteLine("Сообщение: " + message.TextMessage); Dispatcher.Invoke(() => { Correspondence correspondence1 = UsersListBox.SelectedItem as Correspondence; if (correspondence1 != null && correspondence1.Interlocutor.Id == message.SenderId) { DrawingMessage(message); //прочитано сообщение } else { for (int index = 0; index < UsersListBox.Items.Count; index++) { Correspondence correspondence = (UsersListBox.Items[index] as Correspondence); if (correspondence.Interlocutor.Id != message.SenderId) { continue; } correspondence.NumberOfUnreadMessages++; //usersOnlineListBox.Items.Insert(index, correspondence); } UsersListBox.UpdateLayout(); } }); } if (serverMessage is GetAllUsers) { GetAllUsers usersInform = (serverMessage as GetAllUsers); Console.WriteLine("Пришёл список пользователей"); Dispatcher.Invoke(() => { UsersListBox.Items.Clear(); foreach (AccountInformation t in usersInform.AccountsInformation) { UsersListBox.Items.Add(new Correspondence(t)); } }); } if (serverMessage is UserDisconnect) { UserDisconnect ud = (serverMessage as UserDisconnect); Dispatcher.Invoke(() => { if (!OnlineAndAllCheckBox.IsChecked.Value) { for (int i = 0; i < UsersListBox.Items.Count; i++) { if ((UsersListBox.Items[i] as Correspondence).Interlocutor.Id == ud.ThisAccountInforamtion.Id) { UsersListBox.Items.RemoveAt(i); } } } }); } } catch (Exception ex) { //connectionSocket.Disconnect(false); Console.WriteLine(ex.Message + "\n" + ex.StackTrace); return; } } }
private Task UserdisconnectEvent_OnEvent(object sender, UserDisconnect <GameHub> e) { _connectedUsers.TryRemove(e.ConnectionId, out _); return(Task.CompletedTask); }
private static void Listen_client(object socket) { Socket connection_socket = socket as Socket; while (true) { try { object clientMessage; { byte[] clientData = new byte[10000]; if (connection_socket.Receive(clientData) == 0) { continue; } clientMessage = Functions.Deserialize(clientData); //ShowMessage("Получены некие данные", ConsoleColor.Red); } if (clientMessage is Message) { Message message = (clientMessage as Message); if (message.WhetherRead) { int idObject = ManagerAccountsOnline.GetIdObjectMessageByHashCode(message); if (idObject > -1) { ManagerAccountsOnline.Messages[idObject] .WhetherRead = true; } } else { ManagerAccountsOnline.SendMessage(message); } } if (clientMessage is SendEmailRegistration) { SendEmailRegistration message = clientMessage as SendEmailRegistration; SendMessageToEmail(message.Subject, message.Body, message.Email, message.Name + " " + message.Surname, connection_socket); } if (clientMessage is UserDisconnect) { UserDisconnect ud = (clientMessage as UserDisconnect); ManagerAccountsOnline.DeleteUser(ud.ThisAccountInforamtion); connection_socket.Shutdown(SocketShutdown.Both); foreach (Socket sockeT in ManagerAccountsOnline.AccountsOnline.Values) { Functions.SerializeAndSend(ud, sockeT); } return; } if (clientMessage is SocketDisconnect) { connection_socket.Disconnect((clientMessage as SocketDisconnect).ReuseSocket); connection_socket.Shutdown(SocketShutdown.Both); return; } if (clientMessage is AccountInformation) { AccountInformation ai = clientMessage as AccountInformation; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } int sex = 1; if (!ai.ManWoman) { sex = 0; } string query = "INSERT INTO Accounts VALUES ('" + ai.FirstName + "','" + ai.LastName + "'," + sex + ", '" + ai.DateOfBirth.Year + "-" + ai.DateOfBirth.Month + "-" + ai.DateOfBirth.Day + "', '" + ai.Email + "','" + ai.HashPassword + "')"; SqlCommand command = new SqlCommand(query, SqlConnection); command.ExecuteNonQuery(); command.Dispose(); ShowMessage("В базу данных был добавлен новый аккаунт", ConsoleColor.White); SqlConnection.Close(); } if (clientMessage is Authorization) { //Thread.Sleep(4000); Authorization authorization = clientMessage as Authorization; string query = "select * from Accounts where Email='" + authorization.Email + "' and HashPassword='******'"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); SqlDataReader reader = command.ExecuteReader(); reader.Read(); if (reader.HasRows) { bool manWoman = true; if (reader.GetInt32(3) == 0) { manWoman = false; } AccountInformation ai = new AccountInformation(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), manWoman, reader.GetDateTime(4), reader.GetString(5), reader.GetString(6)); Functions.SerializeAndSend(ai, connection_socket); ManagerAccountsOnline.AddUser(ai, connection_socket); } else { AccountInformation accountInformation = new AccountInformation { IsNull = true }; Functions.SerializeAndSend(accountInformation, connection_socket); } reader.Close(); SqlConnection.Close(); } if (clientMessage is UniquenessEmail) { UniquenessEmail uniquenessEmail = (clientMessage as UniquenessEmail); string query = "select Email from Accounts where Email='" + uniquenessEmail.Email + "'"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); SqlDataReader reader = command.ExecuteReader(); reader.Read(); uniquenessEmail.YesNo = reader.HasRows; reader.Close(); SqlConnection.Close(); Functions.SerializeAndSend(uniquenessEmail, connection_socket); } if (clientMessage is GetUsersOnline) { //ShowMessage("Пришёл запрос на получение списка пользователей", ConsoleColor.Red); GetUsersOnline guo = (clientMessage as GetUsersOnline); foreach (AccountInformation ar in ManagerAccountsOnline.AccountsOnline.Keys) { guo.AccountsInformation.Add(ar); } Functions.SerializeAndSend(guo, connection_socket); } if (clientMessage is GetAllUsers) { GetAllUsers gao = (clientMessage as GetAllUsers); string query = "select * from Accounts"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { bool manWoman = true; if (reader.GetInt32(3) == 0) { manWoman = false; } gao.AccountsInformation.Add(new AccountInformation(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), manWoman, reader.GetDateTime(4), reader.GetString(5), reader.GetString(6))); } } reader.Close(); SqlConnection.Close(); Functions.SerializeAndSend(gao, connection_socket); } if (clientMessage is GetMessages) { GetMessages gm = clientMessage as GetMessages; string query = "select * from [Messages] where SenderAccountID=" + gm.SenderId + " and ReceiverAccountID=" + gm.RecieverId + " or SenderAccountID=" + gm.RecieverId + " and ReceiverAccountID=" + gm.SenderId + " order by DateTimeSent"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Message message = new Message(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetString(3), reader.GetDateTime(4), reader.GetBoolean(5)); gm.Messages.Add(message); } Functions.SerializeAndSend(gm, connection_socket); reader.Close(); SqlConnection.Close(); } if (clientMessage is RecoverPasswordMessage) { RecoverPasswordMessage message = (clientMessage as RecoverPasswordMessage); string query = "select * from Accounts where Email='" + message.Email + "'"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); SqlDataReader reader = command.ExecuteReader(); reader.Read(); if (reader.HasRows) { string randomCode = Functions.GetRandomCode(); SendMessageToEmail("Изменение пароля", "Для продолжения введите в программе этот код подтверждения: " + randomCode, message.Email, reader[1] + " " + reader[2], null); Functions.SerializeAndSend(new GetCode(randomCode), connection_socket); } reader.Close(); SqlConnection.Close(); } if (clientMessage is NewPassword) { NewPassword newPassword = (clientMessage as NewPassword); string query = "update Accounts set HashPassword='******' where Email='" + newPassword.Email + "'"; if (SqlConnection.State == ConnectionState.Closed) { SqlConnection.Open(); } SqlCommand command = new SqlCommand(query, SqlConnection); try { command.ExecuteNonQuery(); command.Dispose(); Functions.SerializeAndSend(new MessageFromServer("Пароль был успешно изменён!"), connection_socket); } catch (Exception exception) { ShowMessage(exception.Message, ConsoleColor.Red); } } } catch (SocketException ex) { ShowMessage(ex.Message, ConsoleColor.Red); connection_socket.Disconnect(false); return; //connection_socket.Shutdown(SocketShutdown.Both); } catch (Exception ex) { ShowMessage(ex.ToString(), ConsoleColor.Red); return; } } }