From c339746a82ef7ce961458eda6e1341ed92a9877b Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 21:05:04 +0200 Subject: [PATCH 01/11] [ADD] add closing method --- Client/Views/GameWindow.xaml | 1 + Client/Views/GameWindow.xaml.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/Client/Views/GameWindow.xaml b/Client/Views/GameWindow.xaml index 6614197..7e8c71c 100644 --- a/Client/Views/GameWindow.xaml +++ b/Client/Views/GameWindow.xaml @@ -6,6 +6,7 @@ xmlns:local="clr-namespace:Client.Views" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" mc:Ignorable="d" + Closing="Window_Closing" Title="Scrubl.io" Height="600" Width="1200"> diff --git a/Client/Views/GameWindow.xaml.cs b/Client/Views/GameWindow.xaml.cs index 9d90635..55e8be0 100644 --- a/Client/Views/GameWindow.xaml.cs +++ b/Client/Views/GameWindow.xaml.cs @@ -58,5 +58,10 @@ namespace Client.Views { viewModel.Color_Picker(e, this); } + + private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) + { + + } } } From 442cdccc49433895505c133144735e2aa96ed095 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 21:40:35 +0200 Subject: [PATCH 02/11] [ADD] add updating lobbies on exiting window --- Client/ViewModels/ViewModelGame.cs | 7 ++++++ Client/Views/GameWindow.xaml | 2 -- Client/Views/GameWindow.xaml.cs | 14 ++--------- Server/Models/ServerClient.cs | 5 ++++ Server/Models/ServerCommunication.cs | 36 ++++++++++++++++++++++++++++ SharedClientServer/JSONConvert.cs | 1 - 6 files changed, 50 insertions(+), 15 deletions(-) diff --git a/Client/ViewModels/ViewModelGame.cs b/Client/ViewModels/ViewModelGame.cs index 65fd353..d82df09 100644 --- a/Client/ViewModels/ViewModelGame.cs +++ b/Client/ViewModels/ViewModelGame.cs @@ -4,6 +4,7 @@ using GalaSoft.MvvmLight.Command; using SharedClientServer; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media; @@ -120,6 +121,12 @@ namespace Client.ViewModels data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); } + public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e) + { + Debug.WriteLine("Leaving..."); + data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); + } + } } diff --git a/Client/Views/GameWindow.xaml b/Client/Views/GameWindow.xaml index 7e8c71c..1599e1f 100644 --- a/Client/Views/GameWindow.xaml +++ b/Client/Views/GameWindow.xaml @@ -3,10 +3,8 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" - xmlns:local="clr-namespace:Client.Views" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" mc:Ignorable="d" - Closing="Window_Closing" Title="Scrubl.io" Height="600" Width="1200"> diff --git a/Client/Views/GameWindow.xaml.cs b/Client/Views/GameWindow.xaml.cs index 55e8be0..5947c52 100644 --- a/Client/Views/GameWindow.xaml.cs +++ b/Client/Views/GameWindow.xaml.cs @@ -1,15 +1,8 @@ using Client.ViewModels; -using System; -using System.Collections.Generic; -using System.Text; using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Shapes; + namespace Client.Views { @@ -24,6 +17,7 @@ namespace Client.Views { this.viewModel = new ViewModelGame(); DataContext = this.viewModel; + Closing += this.viewModel.LeaveGame; InitializeComponent(); } @@ -59,9 +53,5 @@ namespace Client.Views viewModel.Color_Picker(e, this); } - private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) - { - - } } } diff --git a/Server/Models/ServerClient.cs b/Server/Models/ServerClient.cs index 90eab73..c6090da 100644 --- a/Server/Models/ServerClient.cs +++ b/Server/Models/ServerClient.cs @@ -166,6 +166,11 @@ namespace Server.Models sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage()); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); break; + case LobbyIdentifier.LEAVE: + id = JSONConvert.GetLobbyID(payload); + ServerCommunication.INSTANCE.LeaveLobby(User, id); + ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); + break; } } diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index 497f901..511f190 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -161,6 +161,31 @@ namespace Server.Models } } + public void RemoveFromLobby(Lobby lobby, User user) + { + foreach (Lobby l in lobbies) + { + if (l == lobby) + { + if (lobby.Users.Contains(user)) + { + Debug.WriteLine("[SERVERCOMM] removed user from lobby!"); + lobby.Users.Remove(user); + foreach (ServerClient sc in serverClients) + { + if (sc.User.Username == user.Username) + { + serverClientsInlobbies[l].Remove(sc); + break; + } + } + } + + } + break; + } + } + public int HostForLobby(User user) { Lobby lobby = new Lobby( lobbies.Count + 1,0, 8); @@ -183,5 +208,16 @@ namespace Server.Models } } } + + public void LeaveLobby(User user, int id) + { + foreach (Lobby l in lobbies) + { + if (l.ID == id) + { + RemoveFromLobby(l, user); + } + } + } } } diff --git a/SharedClientServer/JSONConvert.cs b/SharedClientServer/JSONConvert.cs index dd967e8..9c96f2d 100644 --- a/SharedClientServer/JSONConvert.cs +++ b/SharedClientServer/JSONConvert.cs @@ -139,7 +139,6 @@ namespace SharedClientServer } #endregion - /// /// constructs a message that can be sent to the clients or server /// From cc5c71a30fd7c2ed0b5b946852a5cae9131a6a55 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 21:55:28 +0200 Subject: [PATCH 03/11] [ADD] added buttons reenabled when leaving --- Client/Client.cs | 9 +++++++-- Client/ViewModels/ViewModel.cs | 21 ++++++++------------- Server/Models/ServerClient.cs | 1 + 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index 5346d92..88278ad 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -8,7 +8,7 @@ using static SharedClientServer.JSONConvert; namespace Client { - public delegate void OnLobbyCreated(int id); + public delegate void LobbyCallback(int id); class Client : ObservableObject { private TcpClient tcpClient; @@ -23,7 +23,8 @@ namespace Client public Callback OnLobbiesListReceived; public Callback OnLobbyJoinSuccess; public Callback OnLobbiesReceivedAndWaitingForHost; - public OnLobbyCreated OnLobbyCreated; + public LobbyCallback OnLobbyCreated; + public LobbyCallback OnLobbyLeave; public Lobby[] Lobbies { get; set; } public Client(string username) @@ -118,6 +119,10 @@ namespace Client case LobbyIdentifier.JOIN_SUCCESS: OnLobbyJoinSuccess?.Invoke(); break; + case LobbyIdentifier.LEAVE: + int lobbyLeaveID = JSONConvert.GetLobbyID(payload); + OnLobbyLeave?.Invoke(lobbyLeaveID); + break; } //TODO fill lobby with the data received break; diff --git a/Client/ViewModels/ViewModel.cs b/Client/ViewModels/ViewModel.cs index bbb9843..37d4ed9 100644 --- a/Client/ViewModels/ViewModel.cs +++ b/Client/ViewModels/ViewModel.cs @@ -34,6 +34,7 @@ namespace Client _lobbies = new ObservableCollection(); client = ClientData.Instance.Client; client.OnLobbiesListReceived = updateLobbies; + client.OnLobbyLeave = leaveLobby; OnHostButtonClick = new RelayCommand(hostGame); @@ -41,6 +42,13 @@ namespace Client JoinSelectedLobby = new RelayCommand(joinLobby, true); } + private void leaveLobby(int id) + { + _model.CanStartGame = true; + ClientData.Instance.Lobby = null; + SelectedLobby = null; + } + private void hostGame() { Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username); @@ -96,19 +104,6 @@ namespace Client Lobby[] lobbiesArr = client.Lobbies; Application.Current.Dispatcher.Invoke(delegate { - - //for (int i = 0; i < lobbiesArr.Length; i++) - //{ - // Lobby lobby = lobbiesArr[i]; - // Debug.WriteLine(lobby.PlayersIn); - // if (i < _lobbies.Count && _lobbies[i].ID == lobby.ID) - // { - // _lobbies[i].Set(lobby); - // } else - // { - // _lobbies.Add(lobbiesArr[i]); - // } - //} _lobbies.Clear(); diff --git a/Server/Models/ServerClient.cs b/Server/Models/ServerClient.cs index c6090da..843db9c 100644 --- a/Server/Models/ServerClient.cs +++ b/Server/Models/ServerClient.cs @@ -169,6 +169,7 @@ namespace Server.Models case LobbyIdentifier.LEAVE: id = JSONConvert.GetLobbyID(payload); ServerCommunication.INSTANCE.LeaveLobby(User, id); + sendMessage(JSONConvert.ConstructLobbyLeaveMessage(id)); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); break; } From 9e1ac07b80f39250fc7337d668a97e63436d32eb Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 22:03:20 +0200 Subject: [PATCH 04/11] [ADD] added equals operators --- SharedClientServer/User.cs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/SharedClientServer/User.cs b/SharedClientServer/User.cs index e504418..4a1a36c 100644 --- a/SharedClientServer/User.cs +++ b/SharedClientServer/User.cs @@ -27,6 +27,30 @@ namespace SharedClientServer _host = false; } + public static bool operator ==(User u1, User u2) + { + return u1.Username == u2.Username; + } + + public static bool operator !=(User u1, User u2) + { + return u1.Username != u2.Username; + } + + public override bool Equals(object obj) + { + if ((obj == null) || !this.GetType().Equals(obj.GetType())) + { + return false; + } + else + { + User other = obj as User; + return other.Username == this.Username; + } + } + + public string Username { get { return _username; } From be99c8d3f92e80527b3b230761c64d9dabf4aec2 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 22:18:37 +0200 Subject: [PATCH 05/11] [FIX] fixed equals operators --- SharedClientServer/User.cs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/SharedClientServer/User.cs b/SharedClientServer/User.cs index 4a1a36c..8d45dc2 100644 --- a/SharedClientServer/User.cs +++ b/SharedClientServer/User.cs @@ -1,11 +1,12 @@ using Newtonsoft.Json; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text; namespace SharedClientServer { - class User + class User : IEquatable { private string _username; private int _score; @@ -29,12 +30,20 @@ namespace SharedClientServer public static bool operator ==(User u1, User u2) { - return u1.Username == u2.Username; + if (object.ReferenceEquals(u1, null)) + { + return object.ReferenceEquals(u2, null); + } + return u1.Equals(u2 as object); } public static bool operator !=(User u1, User u2) { - return u1.Username != u2.Username; + if (object.ReferenceEquals(u1, null)) + { + return object.ReferenceEquals(u2, null); + } + return u1.Equals(u2 as object); } public override bool Equals(object obj) @@ -45,11 +54,15 @@ namespace SharedClientServer } else { - User other = obj as User; - return other.Username == this.Username; + return this.Equals(obj as User); + } } - + + public bool Equals([AllowNull] User other) + { + return other.Username == this.Username; + } public string Username { From 8a90e74e74f603739266f914ba528fd9484b7f28 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 22:32:56 +0200 Subject: [PATCH 06/11] [FIX] fixed leaving lobby --- Server/Models/ServerCommunication.cs | 50 ++++++++++++++-------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index 511f190..c461aa1 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -161,30 +161,6 @@ namespace Server.Models } } - public void RemoveFromLobby(Lobby lobby, User user) - { - foreach (Lobby l in lobbies) - { - if (l == lobby) - { - if (lobby.Users.Contains(user)) - { - Debug.WriteLine("[SERVERCOMM] removed user from lobby!"); - lobby.Users.Remove(user); - foreach (ServerClient sc in serverClients) - { - if (sc.User.Username == user.Username) - { - serverClientsInlobbies[l].Remove(sc); - break; - } - } - } - - } - break; - } - } public int HostForLobby(User user) { @@ -211,11 +187,35 @@ namespace Server.Models public void LeaveLobby(User user, int id) { + Debug.WriteLine("[SERVERCOMM] removing user from lobby"); foreach (Lobby l in lobbies) { if (l.ID == id) { - RemoveFromLobby(l, user); + Debug.WriteLine($"[SERVERCOMM] checking for lobby with id {l.ID}"); + + foreach (User u in l.Users) + { + Debug.WriteLine($"[SERVERCOMM] checking if {u.Username} is {user.Username} "); + // contains doesn't work, so we'll do it like this... + if (u.Username == user.Username) + { + Debug.WriteLine("[SERVERCOMM] removed user from lobby!"); + l.Users.Remove(user); + foreach (ServerClient sc in serverClients) + { + if (sc.User.Username == user.Username) + { + serverClientsInlobbies[l].Remove(sc); + break; + } + } + break; + } + } + + + } } } From d5d6d596905b7c896d29116756ca46deff5993c7 Mon Sep 17 00:00:00 2001 From: Dogukan Date: Wed, 21 Oct 2020 22:40:36 +0200 Subject: [PATCH 07/11] [FIX] fixed the broadcast for the chat messages. --- Client/Client.cs | 7 +++++++ Client/ViewModels/ViewModelGame.cs | 14 ++++++++++---- Server/Models/ServerClient.cs | 12 ++++++++---- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index 5346d92..8a51785 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -24,6 +24,7 @@ namespace Client public Callback OnLobbyJoinSuccess; public Callback OnLobbiesReceivedAndWaitingForHost; public OnLobbyCreated OnLobbyCreated; + private ClientData data = ClientData.Instance; public Lobby[] Lobbies { get; set; } public Client(string username) @@ -81,6 +82,7 @@ namespace Client byte[] payload = new byte[message.Length - 5]; Array.Copy(message, 5, payload, 0, message.Length - 5); + Debug.WriteLine("[CLIENT] GOT STRING" + Encoding.ASCII.GetString(payload)); switch (id) { case JSONConvert.LOGIN: @@ -92,6 +94,11 @@ namespace Client string textUsername = combo.Item1; string textMsg = combo.Item2; + if(textUsername != data.User.Username) + { + ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg); + } + //TODO display username and message in chat window Debug.WriteLine("[CLIENT] INCOMING MESSAGE!"); Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg); diff --git a/Client/ViewModels/ViewModelGame.cs b/Client/ViewModels/ViewModelGame.cs index 65fd353..298a7fc 100644 --- a/Client/ViewModels/ViewModelGame.cs +++ b/Client/ViewModels/ViewModelGame.cs @@ -20,13 +20,13 @@ namespace Client.ViewModels private Point currentPoint = new Point(); private Color color; - public ObservableCollection Messages { get; } = new ObservableCollection(); + public static ObservableCollection Messages { get; } = new ObservableCollection(); private dynamic _payload; - private string _username; + public string _username; - private string _message; + public string _message; public string Message { get @@ -120,7 +120,13 @@ namespace Client.ViewModels data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); } - + public static void HandleIncomingMsg(string username, string message) + { + Application.Current.Dispatcher.Invoke(delegate + { + Messages.Add($"{username}: {message}"); + }); + } } } diff --git a/Server/Models/ServerClient.cs b/Server/Models/ServerClient.cs index 90eab73..125c8f7 100644 --- a/Server/Models/ServerClient.cs +++ b/Server/Models/ServerClient.cs @@ -122,11 +122,15 @@ namespace Server.Models string textUsername = combo.Item1; string textMsg = combo.Item2; - Debug.WriteLine("[SERVERCLIENT] User name: {0}\t User message: {1}", textUsername, textMsg); + //Takes the data sent from the client, and then sets it in a data packet to be sent. + dynamic packet = new + { + username = textUsername, + message = textMsg + }; - // todo handle sending to all except this user the username and message to display in chat - serverCom.SendToLobby(ServerCommunication.INSTANCE.GetLobbyForUser(User),payload); - Debug.WriteLine("Payload has been sent!"); + //Sends the incomming message to be broadcast to all of the clients inside the current lobby. + serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet)); break; case JSONConvert.LOBBY: From e8a72e164fb85e0cbbdb9fa8a9ce50a70859f06f Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 22:41:39 +0200 Subject: [PATCH 08/11] add try catch --- Server/Models/ServerClient.cs | 81 +++++++++++++++------------- Server/Models/ServerCommunication.cs | 6 +++ 2 files changed, 51 insertions(+), 36 deletions(-) diff --git a/Server/Models/ServerClient.cs b/Server/Models/ServerClient.cs index 843db9c..69875ba 100644 --- a/Server/Models/ServerClient.cs +++ b/Server/Models/ServerClient.cs @@ -6,6 +6,7 @@ using SharedClientServer; using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Net.Sockets; using System.Text; using static SharedClientServer.JSONConvert; @@ -45,48 +46,56 @@ namespace Server.Models if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected) return; - - int bytesReceived = this.stream.EndRead(ar); - - if (totalBufferReceived + bytesReceived > 1024) + try { - throw new OutOfMemoryException("buffer is too small!"); - } + int bytesReceived = this.stream.EndRead(ar); - // copy the received bytes into the buffer - Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); - // add the bytes we received to the total amount - totalBufferReceived += bytesReceived; - - // calculate the expected length of the message - int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); - - while (totalBufferReceived >= expectedMessageLength) - { - // we have received the full packet - byte[] message = new byte[expectedMessageLength]; - // copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method - Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength); - HandleIncomingMessage(message); - - // move the contents of the totalbuffer to the start of the array - Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); - - // remove the length of the expected message from the total buffer - totalBufferReceived -= expectedMessageLength; - // and set the new expected length to the rest that is still in the buffer - expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); - - if (expectedMessageLength == 0) + if (totalBufferReceived + bytesReceived > 1024) { - break; - } + throw new OutOfMemoryException("buffer is too small!"); + } + // copy the received bytes into the buffer + Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); + // add the bytes we received to the total amount + totalBufferReceived += bytesReceived; + + // calculate the expected length of the message + int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); + + while (totalBufferReceived >= expectedMessageLength) + { + // we have received the full packet + byte[] message = new byte[expectedMessageLength]; + // copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method + Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength); + HandleIncomingMessage(message); + + // move the contents of the totalbuffer to the start of the array + Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength)); + + // remove the length of the expected message from the total buffer + totalBufferReceived -= expectedMessageLength; + // and set the new expected length to the rest that is still in the buffer + expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); + + if (expectedMessageLength == 0) + { + break; + } + + + } + // start reading for a new message + stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); } - // start reading for a new message - stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); - + catch (IOException e) + { + tcpClient.Close(); + ServerCommunication.INSTANCE.ServerClientDisconnect(this); + } + } diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index c461aa1..0447bd2 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -97,6 +97,12 @@ namespace Server.Models } } + public void ServerClientDisconnect(ServerClient serverClient) + { + // remove from serverclientsinlobbies + // send leave message + } + public void SendToAllExcept(string username, byte[] message) { foreach (ServerClient sc in serverClients) From c150bf3611c08e2ad05410f430d6c9305b79b017 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Wed, 21 Oct 2020 22:54:37 +0200 Subject: [PATCH 09/11] [FIX] fixed handling client disconnect --- Server/Models/ServerCommunication.cs | 27 +++++++++++++++++++++++++-- Server/ViewModels/MainViewModel.cs | 4 ++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index 0447bd2..1d22c27 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -16,6 +16,7 @@ namespace Server.Models public bool Started = false; public List lobbies; private Dictionary> serverClientsInlobbies; + internal Action DisconnectClientAction; public Action newClientAction; @@ -99,8 +100,22 @@ namespace Server.Models public void ServerClientDisconnect(ServerClient serverClient) { - // remove from serverclientsinlobbies - // send leave message + Debug.WriteLine("[SERVERCOMM] handling disconnect"); + DisconnectClientAction?.Invoke(); + int id = -1; + foreach (Lobby l in serverClientsInlobbies.Keys) + { + if (serverClientsInlobbies[l].Contains(serverClient)) + { + id = l.ID; + }break; + } + + if (id != -1) + { + LeaveLobby(serverClient.User, id); + SendToAllExcept(serverClient, JSONConvert.ConstructLobbyLeaveMessage(id)); + } } public void SendToAllExcept(string username, byte[] message) @@ -111,6 +126,14 @@ namespace Server.Models } } + public void SendToAllExcept(ServerClient sc, byte[] message) + { + foreach (ServerClient s in serverClients) + { + if (s != sc) s.sendMessage(message); + } + } + public void SendToLobby(Lobby lobby, byte[] message) { foreach (Lobby l in lobbies) diff --git a/Server/ViewModels/MainViewModel.cs b/Server/ViewModels/MainViewModel.cs index ad06638..5d153b8 100644 --- a/Server/ViewModels/MainViewModel.cs +++ b/Server/ViewModels/MainViewModel.cs @@ -33,6 +33,10 @@ namespace Server.ViewModels { InformationModel.ClientsConnected++; }; + serverCommunication.DisconnectClientAction = () => + { + InformationModel.ClientsConnected--; + }; //BitmapImage onlineImg = new BitmapImage(new Uri(@"/img/online.png",UriKind.Relative)); //BitmapImage offlineImg = new BitmapImage(new Uri(@"/img/offline.png", UriKind.Relative)); From 471247827b3f926122fffba34eab12b0e66a8c62 Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Thu, 22 Oct 2020 13:13:57 +0200 Subject: [PATCH 10/11] [ADD] added host user check to join --- Server/Models/ServerCommunication.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index 1d22c27..44c92fe 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -207,6 +207,10 @@ namespace Server.Models { if (l.ID == id) { + if (l.Users.Count == 0) + { + user.Host = true; + } AddToLobby(l, user); Debug.WriteLine($"{user.Username} joined lobby with id {id}"); break; From 0b72c4dc9b6ea4024175a7b67580af3037be2b7b Mon Sep 17 00:00:00 2001 From: Sem van der Hoeven Date: Thu, 22 Oct 2020 13:22:52 +0200 Subject: [PATCH 11/11] [ADD] added that when you join an empty lobby you become the host --- Client/Client.cs | 6 ++++-- Client/ViewModels/ViewModel.cs | 6 +++--- Server/Models/ServerClient.cs | 5 +++-- Server/Models/ServerCommunication.cs | 4 +++- SharedClientServer/JSONConvert.cs | 11 +++++++++-- 5 files changed, 22 insertions(+), 10 deletions(-) diff --git a/Client/Client.cs b/Client/Client.cs index bc7b2b5..a86ba3e 100644 --- a/Client/Client.cs +++ b/Client/Client.cs @@ -9,6 +9,7 @@ using static SharedClientServer.JSONConvert; namespace Client { public delegate void LobbyCallback(int id); + public delegate void LobbyJoinCallback(bool isHost); class Client : ObservableObject { private TcpClient tcpClient; @@ -21,7 +22,7 @@ namespace Client private string username; public Callback OnSuccessfullConnect; public Callback OnLobbiesListReceived; - public Callback OnLobbyJoinSuccess; + public LobbyJoinCallback OnLobbyJoinSuccess; public Callback OnLobbiesReceivedAndWaitingForHost; public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyLeave; @@ -124,7 +125,8 @@ namespace Client OnLobbyCreated?.Invoke(lobbyCreatedID); break; case LobbyIdentifier.JOIN_SUCCESS: - OnLobbyJoinSuccess?.Invoke(); + + OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload)); break; case LobbyIdentifier.LEAVE: int lobbyLeaveID = JSONConvert.GetLobbyID(payload); diff --git a/Client/ViewModels/ViewModel.cs b/Client/ViewModels/ViewModel.cs index 37d4ed9..32e65d8 100644 --- a/Client/ViewModels/ViewModel.cs +++ b/Client/ViewModels/ViewModel.cs @@ -85,14 +85,14 @@ namespace Client private void joinLobby() { - // lobby die je wilt joinen verwijderen - // nieuwe binnengekregen lobby toevoegen + client.OnLobbyJoinSuccess = OnLobbyJoinSuccess; client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID)); } - private void OnLobbyJoinSuccess() + private void OnLobbyJoinSuccess(bool isHost) { + ClientData.Instance.User.Host = isHost; startGameInLobby(); } diff --git a/Server/Models/ServerClient.cs b/Server/Models/ServerClient.cs index e264363..05eca4f 100644 --- a/Server/Models/ServerClient.cs +++ b/Server/Models/ServerClient.cs @@ -175,8 +175,9 @@ namespace Server.Models break; case LobbyIdentifier.JOIN: int id = JSONConvert.GetLobbyID(payload); - ServerCommunication.INSTANCE.JoinLobby(this.User,id); - sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage()); + bool isHost; + ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost); + sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost)); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); break; case LobbyIdentifier.LEAVE: diff --git a/Server/Models/ServerCommunication.cs b/Server/Models/ServerCommunication.cs index 44c92fe..dffe07f 100644 --- a/Server/Models/ServerCommunication.cs +++ b/Server/Models/ServerCommunication.cs @@ -201,8 +201,9 @@ namespace Server.Models return lobby.ID; } - public void JoinLobby(User user, int id) + public void JoinLobby(User user, int id, out bool isHost) { + isHost = false; foreach (Lobby l in lobbies) { if (l.ID == id) @@ -210,6 +211,7 @@ namespace Server.Models if (l.Users.Count == 0) { user.Host = true; + isHost = true; } AddToLobby(l, user); Debug.WriteLine($"{user.Username} joined lobby with id {id}"); diff --git a/SharedClientServer/JSONConvert.cs b/SharedClientServer/JSONConvert.cs index 9c96f2d..9ab0900 100644 --- a/SharedClientServer/JSONConvert.cs +++ b/SharedClientServer/JSONConvert.cs @@ -133,9 +133,16 @@ namespace SharedClientServer return dynamicAsObject.ToObject(); } - public static byte[] ConstructLobbyJoinSuccessMessage() + public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost) { - return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS}); + return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS, + host = isHost}); + } + + public static bool GetLobbyJoinIsHost(byte[] json) + { + dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); + return payload.host; } #endregion