20 Commits

Author SHA1 Message Date
Dogukan
4d3dda023c Merge branch 'master' into feature/handleChatData 2020-10-21 22:43:18 +02:00
Dogukan
d5d6d59690 [FIX] fixed the broadcast for the chat messages. 2020-10-21 22:40:36 +02:00
SemvdH
754c1c5db9 Merge pull request #2 from SemvdH/feature/leaveLobby
merge Feature/leave lobby into master
2020-10-21 22:34:27 +02:00
Sem van der Hoeven
8a90e74e74 [FIX] fixed leaving lobby 2020-10-21 22:32:56 +02:00
Sem van der Hoeven
be99c8d3f9 [FIX] fixed equals operators 2020-10-21 22:18:37 +02:00
Sem van der Hoeven
9e1ac07b80 [ADD] added equals operators 2020-10-21 22:03:20 +02:00
Sem van der Hoeven
cc5c71a30f [ADD] added buttons reenabled when leaving 2020-10-21 21:55:28 +02:00
Sem van der Hoeven
442cdccc49 [ADD] add updating lobbies on exiting window 2020-10-21 21:40:35 +02:00
Sem van der Hoeven
c339746a82 [ADD] add closing method 2020-10-21 21:05:04 +02:00
SemvdH
0f01354b72 Merge pull request #1 from SemvdH/setupBranch
merge Setup branch into develop
2020-10-21 20:59:02 +02:00
Sem van der Hoeven
61577e0df7 [FIX] fixed merge conflicts 2020-10-21 20:56:38 +02:00
Sem van der Hoeven
298bd760e5 Merge remote-tracking branch 'origin/feature/sendingCanvasData' into setupBranch 2020-10-21 20:45:51 +02:00
Sem van der Hoeven
c4c97a3fbe Merge branch 'lobbies' into setupBranch 2020-10-21 20:44:11 +02:00
Dogukan
a4e45b1a6b [MISC] tried to send the message to the current lobby, didn't work. 2020-10-21 20:43:28 +02:00
Lars
4f07eeb95a useless 2020-10-21 20:24:26 +02:00
Dogukan
74f8e868f6 [ADDITION] servercommunication towards the client.
Still in progress not functional because of a null exception when receiving the broadcast message.
2020-10-21 17:47:48 +02:00
Dogukan
381c142eaa [ADDITION] Added databinding to the chatbox function.
Tried to broadcast the message, doesn't work yet.
2020-10-20 23:54:29 +02:00
Lars
2aeca40aa4 its not working yet, its getting a System.OutOfMemoryException, needs to be fixed 2020-10-20 23:52:10 +02:00
Dogukan
4d161391b1 Merge remote-tracking branch 'origin/setupBranch' into setupBranch 2020-10-20 19:53:35 +02:00
Dogukan
7dbdcc8bcc [ADDITION] fixed the chatbox size 2020-10-20 19:53:28 +02:00
12 changed files with 294 additions and 112 deletions

View File

@@ -8,7 +8,7 @@ using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void OnLobbyCreated(int id); public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
private TcpClient tcpClient; private TcpClient tcpClient;
@@ -23,7 +23,9 @@ namespace Client
public Callback OnLobbiesListReceived; public Callback OnLobbiesListReceived;
public Callback OnLobbyJoinSuccess; public Callback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public OnLobbyCreated OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave;
private ClientData data = ClientData.Instance;
public Lobby[] Lobbies { get; set; } public Lobby[] Lobbies { get; set; }
public Client(string username) public Client(string username)
@@ -72,14 +74,16 @@ namespace Client
} }
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
private void handleData(byte[] message) private void handleData(byte[] message)
{ {
byte id = message[4]; byte id = message[4];
byte[] payload = new byte[message.Length - 5]; byte[] payload = new byte[message.Length - 5];
Array.Copy(message, 5, payload, 0, message.Length - 5); Array.Copy(message, 5, payload, 0, message.Length - 5);
Debug.WriteLine("[CLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
switch (id) switch (id)
{ {
case JSONConvert.LOGIN: case JSONConvert.LOGIN:
@@ -90,8 +94,15 @@ namespace Client
(string, string) combo = JSONConvert.GetUsernameAndMessage(payload); (string, string) combo = JSONConvert.GetUsernameAndMessage(payload);
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
//TODO display username and message in chat window
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);
break; break;
case JSONConvert.LOBBY: case JSONConvert.LOBBY:
@@ -115,12 +126,18 @@ namespace Client
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke(); OnLobbyJoinSuccess?.Invoke();
break; break;
case LobbyIdentifier.LEAVE:
int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
OnLobbyLeave?.Invoke(lobbyLeaveID);
break;
} }
//TODO fill lobby with the data received //TODO fill lobby with the data received
break; break;
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
// canvas data // canvas data
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;

View File

@@ -30,6 +30,7 @@ namespace Client
private User _user; private User _user;
private Client _client; private Client _client;
private Lobby _lobby; private Lobby _lobby;
private string _message;
private ClientData() private ClientData()
{ {
@@ -55,5 +56,17 @@ namespace Client
set { _lobby = value; } set { _lobby = value; }
} }
public String Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
} }
} }

View File

@@ -34,6 +34,7 @@ namespace Client
_lobbies = new ObservableCollection<Lobby>(); _lobbies = new ObservableCollection<Lobby>();
client = ClientData.Instance.Client; client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies; client.OnLobbiesListReceived = updateLobbies;
client.OnLobbyLeave = leaveLobby;
OnHostButtonClick = new RelayCommand(hostGame); OnHostButtonClick = new RelayCommand(hostGame);
@@ -41,6 +42,13 @@ namespace Client
JoinSelectedLobby = new RelayCommand(joinLobby, true); JoinSelectedLobby = new RelayCommand(joinLobby, true);
} }
private void leaveLobby(int id)
{
_model.CanStartGame = true;
ClientData.Instance.Lobby = null;
SelectedLobby = null;
}
private void hostGame() private void hostGame()
{ {
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username); Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
@@ -96,19 +104,6 @@ namespace Client
Lobby[] lobbiesArr = client.Lobbies; Lobby[] lobbiesArr = client.Lobbies;
Application.Current.Dispatcher.Invoke(delegate 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(); _lobbies.Clear();

View File

@@ -1,10 +1,140 @@
using System.Collections.ObjectModel;
using System.ComponentModel; using Client.Views;
using GalaSoft.MvvmLight.Command;
namespace Client.ViewModels using SharedClientServer;
{ using System.Collections.ObjectModel;
class ViewModelGame : INotifyPropertyChanged using System.ComponentModel;
{ using System.Diagnostics;
public event PropertyChangedEventHandler PropertyChanged; using System.Windows;
} using System.Windows.Input;
} using System.Windows.Media;
using System.Windows.Shapes;
namespace Client.ViewModels
{
class ViewModelGame : INotifyPropertyChanged
{
private ClientData data = ClientData.Instance;
public event PropertyChangedEventHandler PropertyChanged;
private Point currentPoint = new Point();
private Color color;
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
private dynamic _payload;
public string _username;
public string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
public ICommand OnKeyDown { get; set; }
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
{
if (e.ButtonState == MouseButtonState.Pressed)
{
currentPoint = e.GetPosition(window.CanvasForPaint);
}
}
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
double[] coordinates = new double[4];
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(window.CanvasForPaint).X;
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
coordinates[0] = line.X1;
coordinates[1] = line.Y1;
coordinates[2] = line.X2;
coordinates[3] = line.Y2;
currentPoint = e.GetPosition(window.CanvasForPaint);
window.CanvasForPaint.Children.Add(line);
data.Client.SendMessage(JSONConvert.GetMessageToSend(0x04, coordinates));
}
}
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
}
public ViewModelGame()
{
if (_payload == null)
{
_message = "";
}
else
{
//_message = data.Message;
//_username = data.User.Username;
//Messages.Add($"{data.User.Username}: {Message}");
}
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
}
private void ChatBox_KeyDown()
{
//if enter then clear textbox and send message.
if (Message != string.Empty) AddMessage(Message);
Message = string.Empty;
}
internal void AddMessage(string message)
{
Messages.Add($"{data.User.Username}: {message}");
_payload = new
{
username = data.User.Username,
message = message
};
//Broadcast the message after adding it to the list!
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}");
});
}
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
}
}
}

View File

@@ -3,7 +3,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Client.Views"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d" mc:Ignorable="d"
Title="Scrubl.io" Height="600" Width="1200"> Title="Scrubl.io" Height="600" Width="1200">
@@ -48,8 +47,13 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<TextBox Name="SentMessage" IsReadOnly="True"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/>
<TextBox x:Name="ChatBox" Keyboard.KeyDown="ChatBox_KeyDown" Width="200" Height="50" ToolTip="Message goes here" ToolTipService.IsEnabled="True" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0">
<TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings>
</TextBox>
</Grid> </Grid>
</Grid> </Grid>

View File

@@ -1,15 +1,8 @@
using Client.ViewModels; using Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Client.Views namespace Client.Views
{ {
@@ -19,54 +12,25 @@ namespace Client.Views
public partial class GameWindow : Window public partial class GameWindow : Window
{ {
ClientData data = ClientData.Instance; ClientData data = ClientData.Instance;
private ViewModelGame viewModel;
public GameWindow() public GameWindow()
{ {
DataContext = new ViewModelGame(); this.viewModel = new ViewModelGame();
DataContext = this.viewModel;
Closing += this.viewModel.LeaveGame;
InitializeComponent(); InitializeComponent();
} }
Point currentPoint = new Point();
private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e) private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e)
{ {
if (e.ButtonState == MouseButtonState.Pressed) this.viewModel.Canvas_MouseDown(e, this);
{
currentPoint = e.GetPosition(CanvasForPaint);
}
} }
private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e) private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e)
{ {
if (e.LeftButton == MouseButtonState.Pressed) viewModel.Canvas_MouseMove(e, this);
{
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(CanvasForPaint).X;
line.Y2 = e.GetPosition(CanvasForPaint).Y;
currentPoint = e.GetPosition(CanvasForPaint);
CanvasForPaint.Children.Add(line);
}
}
private Color color;
private void ClrPcker_Background_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
} }
private void CanvasReset_Click(object sender, RoutedEventArgs e) private void CanvasReset_Click(object sender, RoutedEventArgs e)
@@ -82,41 +46,12 @@ namespace Client.Views
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement; // var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
// TEST.Children.Add(deepCopy); // TEST.Children.Add(deepCopy);
//} //}
} }
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e) private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
{ {
Color colorSelected = new Color(); viewModel.Color_Picker(e, this);
colorSelected.A = 255;
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
} }
private void ChatBox_KeyDown(object sender, KeyEventArgs e)
{
//if enter then clear textbox and send message.
if (e.Key.Equals(Key.Enter))
{
WriteToChat(ChatBox.Text);
ChatBox.Clear();
}
}
/*
* Writes the current client's message to the chatbox.
*/
private void WriteToChat(string message)
{
string user = data.User.Username;
SentMessage.AppendText($"{user}: {message}\n");
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
} }
} }

View File

@@ -32,8 +32,6 @@ namespace Client
private void Button_Click(object sender, RoutedEventArgs e) private void Button_Click(object sender, RoutedEventArgs e)
{ {
} }
} }
} }

View File

@@ -1,5 +1,7 @@
 
using Client; using Client;
using Newtonsoft.Json.Linq;
using SharedClientServer; using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -18,6 +20,7 @@ namespace Server.Models
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[1024];
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public User User { get; set; } public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
/// <summary> /// <summary>
@@ -84,6 +87,7 @@ namespace Server.Models
// start reading for a new message // start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
/// <summary> /// <summary>
@@ -118,7 +122,15 @@ namespace Server.Models
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
// todo handle sending to all except this user the username and message to display in chat //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
};
//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; break;
case JSONConvert.LOBBY: case JSONConvert.LOBBY:
@@ -127,6 +139,7 @@ namespace Server.Models
handleLobbyMessage(payload,l); handleLobbyMessage(payload,l);
break; break;
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
// canvas data // canvas data
// todo send canvas data to all other serverclients in lobby // todo send canvas data to all other serverclients in lobby
break; break;
@@ -157,6 +170,12 @@ namespace Server.Models
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage()); sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break; break;
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;
} }
} }

View File

@@ -1,5 +1,4 @@
 using Client;
using Client;
using SharedClientServer; using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -162,6 +161,7 @@ namespace Server.Models
} }
} }
public int HostForLobby(User user) public int HostForLobby(User user)
{ {
Lobby lobby = new Lobby( lobbies.Count + 1,0, 8); Lobby lobby = new Lobby( lobbies.Count + 1,0, 8);
@@ -184,5 +184,40 @@ 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)
{
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;
}
}
}
}
}
} }
} }

View File

@@ -18,6 +18,5 @@ namespace SharedClientServer
Array.Copy(stringAsBytes, 0, res, 1, stringAsBytes.Length); Array.Copy(stringAsBytes, 0, res, 1, stringAsBytes.Length);
return res; return res;
} }
} }
} }

View File

@@ -139,7 +139,6 @@ namespace SharedClientServer
} }
#endregion #endregion
/// <summary> /// <summary>
/// constructs a message that can be sent to the clients or server /// constructs a message that can be sent to the clients or server
/// </summary> /// </summary>

View File

@@ -1,15 +1,17 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text; using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
class User class User : IEquatable<User>
{ {
private string _username; private string _username;
private int _score; private int _score;
private bool _host; private bool _host;
private string _message;
[JsonConstructor] [JsonConstructor]
public User(string username, int score, bool host) public User(string username, int score, bool host)
@@ -26,6 +28,42 @@ namespace SharedClientServer
_host = false; _host = false;
} }
public static bool operator ==(User u1, User u2)
{
if (object.ReferenceEquals(u1, null))
{
return object.ReferenceEquals(u2, null);
}
return u1.Equals(u2 as object);
}
public static bool operator !=(User u1, User u2)
{
if (object.ReferenceEquals(u1, null))
{
return object.ReferenceEquals(u2, null);
}
return u1.Equals(u2 as object);
}
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
return this.Equals(obj as User);
}
}
public bool Equals([AllowNull] User other)
{
return other.Username == this.Username;
}
public string Username public string Username
{ {
get { return _username; } get { return _username; }