Merge branch 'master' into setupBranch

This commit is contained in:
Lars
2020-10-23 13:11:56 +02:00
10 changed files with 427 additions and 337 deletions

View File

@@ -5,16 +5,22 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows.Media; using System.Windows.Media;
using System.Windows; using System.Windows;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyJoinCallback(bool isHost); public delegate void LobbyJoinCallback(bool isHost);
public delegate void CanvasDataReceived(double[] coordinates, Color color);
public delegate void RandomWord(string word);
public delegate void HandleIncomingMsg(string username, string msg);
internal delegate void HandleIncomingPlayer(Lobby lobby);
public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset(); public delegate void CanvasReset();
public delegate void LobbyCallback(int id); public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
@@ -33,8 +39,12 @@ namespace Client
public LobbyJoinCallback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect; public Callback OnServerDisconnect;
public Callback OnLobbyUpdate;
public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave; public LobbyCallback OnLobbyLeave;
public RandomWord RandomWord;
public HandleIncomingMsg IncomingMsg;
public HandleIncomingPlayer IncomingPlayer;
private ClientData data = ClientData.Instance; private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived; public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset; public CanvasReset CReset;
@@ -56,6 +66,7 @@ namespace Client
this.tcpClient.EndConnect(ar); this.tcpClient.EndConnect(ar);
this.stream = tcpClient.GetStream(); this.stream = tcpClient.GetStream();
OnSuccessfullConnect?.Invoke(); OnSuccessfullConnect?.Invoke();
OnLobbyUpdate = updateGameLobby;
SendMessage(JSONConvert.ConstructUsernameMessage(username)); SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null); this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null);
@@ -68,17 +79,20 @@ namespace Client
private void OnReadComplete(IAsyncResult ar) private void OnReadComplete(IAsyncResult ar)
{ {
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return; return;
try try
{ {
int amountReceived = stream.EndRead(ar); int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 1024) if (totalBufferReceived + amountReceived > 2048)
{ {
throw new OutOfMemoryException("buffer too small"); throw new OutOfMemoryException("buffer too small");
} }
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived; totalBufferReceived += amountReceived;
@@ -90,7 +104,6 @@ namespace Client
byte[] message = new byte[expectedMessageLength]; byte[] message = new byte[expectedMessageLength];
// put the message received into the message array // put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength); Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message); handleData(message);
totalBufferReceived -= expectedMessageLength; totalBufferReceived -= expectedMessageLength;
@@ -104,7 +117,6 @@ namespace Client
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message); Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke(); OnServerDisconnect?.Invoke();
} }
} }
private void handleData(byte[] message) private void handleData(byte[] message)
@@ -128,7 +140,7 @@ namespace Client
if(textUsername != data.User.Username) if(textUsername != data.User.Username)
{ {
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg); IncomingMsg?.Invoke(textUsername, textMsg);
} }
//TODO display username and message in chat window //TODO display username and message in chat window
@@ -146,6 +158,7 @@ namespace Client
Lobbies = JSONConvert.GetLobbiesFromMessage(payload); Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
OnLobbiesListReceived?.Invoke(); OnLobbiesListReceived?.Invoke();
OnLobbiesReceivedAndWaitingForHost?.Invoke(); OnLobbiesReceivedAndWaitingForHost?.Invoke();
OnLobbyUpdate?.Invoke();
break; break;
case LobbyIdentifier.HOST: case LobbyIdentifier.HOST:
// we receive this when the server has made us a host of a new lobby // we receive this when the server has made us a host of a new lobby
@@ -155,7 +168,6 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID); OnLobbyCreated?.Invoke(lobbyCreatedID);
break; break;
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload)); OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
@@ -169,25 +181,30 @@ namespace Client
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
// canvas data // canvas data
//clientData.CanvasData = JSONConvert.getCoordinates(payload); //clientData.CanvasData = JSONConvert.getCoordinates(payload);
CanvasInfo type = JSONConvert.GetCanvasMessageType(payload); int type = JSONConvert.GetCanvasMessageType(payload);
switch (type) switch (type)
{ {
case CanvasInfo.RESET: case JSONConvert.CANVAS_RESET:
CReset?.Invoke(); CReset?.Invoke();
break; break;
case CanvasInfo.DRAWING: case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload)); CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
break; // we hebben gedrawed, dus stuur dat we weer kunnen drawen
break;
} }
break; break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload); int lobbyId = JSONConvert.GetLobbyID(payload);
string randomWord = JSONConvert.GetRandomWord(payload);
if(data.Lobby?.ID == lobbyId) if (data.Lobby?.ID == lobbyId)
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload)); RandomWord?.Invoke(randomWord);
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
@@ -197,11 +214,20 @@ namespace Client
} }
private void updateGameLobby()
{
foreach (var item in Lobbies)
{
Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count);
if (item.ID == data.Lobby?.ID)
IncomingPlayer?.Invoke(item);
}
}
public void SendMessage(byte[] message) public void SendMessage(byte[] message)
{ {
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message)); Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message));
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null); stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null);
} }
private void OnWriteComplete(IAsyncResult ar) private void OnWriteComplete(IAsyncResult ar)

View File

@@ -11,10 +11,10 @@ using System.Collections.ObjectModel;
using Client.Views; using Client.Views;
using System.Linq; using System.Linq;
using System.Windows.Data; using System.Windows.Data;
using System.Data; using System.Data;
using System.Windows.Controls.Primitives; using System.Windows.Controls.Primitives;
using System.Windows.Controls; using System.Windows.Controls;
namespace Client namespace Client
{ {
class ViewModel : INotifyPropertyChanged class ViewModel : INotifyPropertyChanged
@@ -92,16 +92,14 @@ namespace Client
private void joinLobby() private void joinLobby()
{ {
// lobby die je wilt joinen verwijderen if (SelectedLobby != null)
// nieuwe binnengekregen lobby toevoegen {
if (SelectedLobby != null) if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
{ {
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable) return;
{ }
return; client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
} client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
} }
} }

View File

@@ -1,203 +1,263 @@
using Client.Views;
using Client.Views; using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Command; using SharedClientServer;
using SharedClientServer; using System;
using System; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Windows; using System.Timers;
using System.Windows.Controls; using System.Windows;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes; using System.Windows.Shapes;
namespace Client.ViewModels namespace Client.ViewModels
{ {
class ViewModelGame : INotifyPropertyChanged class ViewModelGame : INotifyPropertyChanged
{ {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
private ClientData data = ClientData.Instance; private ClientData data = ClientData.Instance;
private GameWindow window; private GameWindow window;
private Point currentPoint = new Point(); private Point currentPoint = new Point();
private Color color; public Color color;
public double[][] buffer;
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public int pos = 0;
public int maxLines = 50;
private dynamic _payload; public Queue<double[][]> linesQueue;
private Timer queueTimer;
public static string Word
{ public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
get; public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
set;
} private dynamic _payload;
public string _username; public string _username;
public string _message; public string _message;
public string Message public string Message
{ {
get get
{ {
return _message; return _message;
} }
set set
{ {
_message = value; _message = value;
} }
} }
public bool IsHost private string _randomWord;
{
get { return data.User.Host; } public string RandomWord
} {
get { return _randomWord; }
public ViewModelGame(GameWindow window) set { _randomWord = value; }
{ }
this.window = window;
if (_payload == null) public static string Word
{ {
_message = ""; get;
set;
} }
else
{ public bool IsHost
//_message = data.Message; {
//_username = data.User.Username; get { return data.User.Host; }
//Messages.Add($"{data.User.Username}: {Message}"); }
}
OnKeyDown = new RelayCommand(ChatBox_KeyDown); public ViewModelGame(GameWindow window)
ButtonStartGame = new RelayCommand(BeginGame); {
ButtonResetCanvas = new RelayCommand(CanvasResetLocal); this.window = window;
data.Client.CanvasDataReceived = UpdateCanvasWithNewData; if (_payload == null)
data.Client.CReset = CanvasResetData; {
} _message = "";
public ICommand OnKeyDown { get; set; } }
public ICommand ButtonStartGame { get; set; } else
public ICommand ButtonResetCanvas { get; set; } {
//_message = data.Message;
public void BeginGame() //_username = data.User.Username;
{ //Messages.Add($"{data.User.Username}: {Message}");
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID)); }
}
buffer = new double[maxLines][];
linesQueue = new Queue<double[][]>();
private void CanvasResetLocal() OnKeyDown = new RelayCommand(ChatBox_KeyDown);
{ ButtonStartGame = new RelayCommand(BeginGame);
this.window.CanvasForPaint.Children.Clear(); ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CanvasInfo.RESET)); data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
} data.Client.CReset = CanvasResetData;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window) data.Client.IncomingPlayer = HandleIncomingPlayer;
{ }
if (e.ButtonState == MouseButtonState.Pressed)
{ public ICommand OnKeyDown { get; set; }
currentPoint = e.GetPosition(window.CanvasForPaint); public ICommand ButtonStartGame { get; set; }
} public ICommand ButtonResetCanvas { get; set; }
}
public void BeginGame()
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window) {
{
if (e.LeftButton == MouseButtonState.Pressed) queueTimer = new Timer(50);
{ queueTimer.Start();
double[] coordinates = new double[4]; queueTimer.Elapsed += sendArrayFromQueue;
Line line = new Line(); data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
}
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X; private void CanvasResetLocal()
line.Y1 = currentPoint.Y; {
line.X2 = e.GetPosition(window.CanvasForPaint).X; this.window.CanvasForPaint.Children.Clear();
line.Y2 = e.GetPosition(window.CanvasForPaint).Y; data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
coordinates[0] = line.X1; }
coordinates[1] = line.Y1;
coordinates[2] = line.X2;
coordinates[3] = line.Y2; public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
currentPoint = e.GetPosition(window.CanvasForPaint); {
if (e.ButtonState == MouseButtonState.Pressed)
window.CanvasForPaint.Children.Add(line); {
data.Client.SendMessage(JSONConvert.ConstructCanvasDataSend(JSONConvert.CanvasInfo.DRAWING,coordinates, color)); currentPoint = e.GetPosition(window.CanvasForPaint);
} }
} }
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window) public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
{ {
Color colorSelected = new Color(); if (e.LeftButton == MouseButtonState.Pressed)
colorSelected.A = 255; {
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R; double[] coordinates = new double[4];
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G; Line line = new Line();
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected; line.Stroke = new SolidColorBrush(color);
} //line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
private void UpdateCanvasWithNewData(double[] coordinates, Color color) line.Y1 = currentPoint.Y;
{ line.X2 = e.GetPosition(window.CanvasForPaint).X;
Application.Current.Dispatcher.Invoke(delegate line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
{ coordinates[0] = line.X1;
Line line = new Line(); coordinates[1] = line.Y1;
line.Stroke = new SolidColorBrush(color); coordinates[2] = line.X2;
line.X1 = coordinates[0]; coordinates[3] = line.Y2;
line.Y1 = coordinates[1]; currentPoint = e.GetPosition(window.CanvasForPaint);
line.X2 = coordinates[2]; buffer[pos] = coordinates;
line.Y2 = coordinates[3]; pos++;
this.window.CanvasForPaint.Children.Add(line);
}); window.CanvasForPaint.Children.Add(line);
} if (pos == maxLines)
{
private void CanvasResetData() double[][] temp = new double[maxLines][];
{ for (int i = 0; i < maxLines; i++)
this.window.CanvasForPaint.Children.Clear(); {
} temp[i] = buffer[i];
}
private void ChatBox_KeyDown() linesQueue.Enqueue(temp);
{ Array.Clear(buffer, 0, buffer.Length);
//if enter then clear textbox and send message. pos = 0;
if (Message != string.Empty) AddMessage(Message); }
Message = string.Empty;
} }
}
internal void AddMessage(string message)
{ public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
Messages.Add($"{data.User.Username}: {message}"); {
sendArrayFromQueue(sender, null);
_payload = new }
{
username = data.User.Username, private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
message = message {
};
if (linesQueue.Count != 0)
//Broadcast the message after adding it to the list! {
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); double[][] temp = linesQueue.Dequeue();
} data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
}
/* }
* MISC make this a callback
* Handles the incoming chat message from another client. public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
*/ {
public static void HandleIncomingMsg(string username, string message) Color colorSelected = new Color();
{ colorSelected.A = 255;
Application.Current.Dispatcher.Invoke(delegate colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
{ colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
Messages.Add($"{username}: {message}"); colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
}); color = colorSelected;
} }
public void LeaveGame(object sender, CancelEventArgs e)
{ private void UpdateCanvasWithNewData(double[][] buffer, Color color)
Debug.WriteLine("Leaving..."); {
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); Application.Current.Dispatcher.Invoke(delegate
} {
foreach (double[] arr in buffer)
/* {
* MISC make this a callback Line line = new Line();
* Handles the random word that has been received from the server. line.Stroke = new SolidColorBrush(color);
*/ line.X1 = arr[0];
public static void HandleRandomWord(string randomWord) line.Y1 = arr[1];
{ line.X2 = arr[2];
Debug.WriteLine("[CLIENT] Reached the handle random word method!"); line.Y2 = arr[3];
Word = "NegerPik"; this.window.CanvasForPaint.Children.Add(line);
} }
} });
} }
private void CanvasResetData()
{
this.window.CanvasForPaint.Children.Clear();
}
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));
}
public static void HandleRandomWord(string randomWord)
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Application.Current.Dispatcher.Invoke(delegate
{
Word = randomWord;
});
}
public void HandleIncomingPlayer(Lobby lobby)
{
Application.Current.Dispatcher.Invoke(delegate
{
Players.Clear();
foreach (var item in lobby.Users)
{
Players.Add(item.Username);
}
});
}
}
}

View File

@@ -22,16 +22,9 @@
<Grid Grid.Column="0" Grid.Row="1"> <Grid Grid.Column="0" Grid.Row="1">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition/> <RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ListBox Name="PlayerList" ItemsSource="{Binding Path=Players}" Margin="10,0,0,10" FontSize="20"/>
</Grid> </Grid>
<Grid Grid.Row="0" Grid.Column="1"> <Grid Grid.Row="0" Grid.Column="1">
@@ -44,6 +37,9 @@
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/> <Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/> <xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=RandomWord, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/> <Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/> <Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
@@ -53,7 +49,7 @@
<Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5"> <Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove"> <Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove" MouseUp="CanvasForPaint_MouseUp">
<Canvas.Background> <Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/> <SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background> </Canvas.Background>
@@ -61,9 +57,9 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,10,69" />
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0"> <TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,10,0">
<TextBox.InputBindings> <TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/> <KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings> </TextBox.InputBindings>

View File

@@ -36,16 +36,6 @@ namespace Client.Views
private void CanvasReset_Click(object sender, RoutedEventArgs e) private void CanvasReset_Click(object sender, RoutedEventArgs e)
{ {
CanvasForPaint.Children.Clear(); CanvasForPaint.Children.Clear();
//FOR FUTURE USE, IF NECCESSARY
//TEST.Children.Clear();
//foreach (UIElement child in CanvasForPaint.Children)
//{
// var xaml = System.Windows.Markup.XamlWriter.Save(child);
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
// 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)
@@ -53,5 +43,9 @@ namespace Client.Views
viewModel.Color_Picker(e, this); viewModel.Color_Picker(e, this);
} }
private void CanvasForPaint_MouseUp(object sender, MouseButtonEventArgs e)
{
viewModel.Canvas_MouseUp(sender, e);
}
} }
} }

View File

@@ -11,6 +11,7 @@
<RowDefinition Height="60"/> <RowDefinition Height="60"/>
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
<RowDefinition Height="30"/> <RowDefinition Height="30"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -22,8 +23,9 @@
<Label Grid.Row="1" FontSize="30" Content="Enter a username:"/> <Label Grid.Row="1" FontSize="30" Content="Enter a username:"/>
<Label Grid.Row="2" FontSize="15" Content="(max amount of characters for the username is 10)"/> <Label Grid.Row="2" FontSize="15" Content="(max amount of characters for the username is 10)"/>
<TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="10" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Left" Width="250"/> <TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="69" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Left" Width="250"/>
<Button Name="loginButton" Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/> <Button Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/>
<Label Grid.Row="3" Grid.Column="0" Content="Tip of the century: base64 != UTF8!" FontSize="20" FontWeight="Bold"/>
</Grid> </Grid>
</Window> </Window>

View File

@@ -1,4 +1,5 @@
using SharedClientServer; using Client.ViewModels;
using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;

View File

@@ -54,11 +54,12 @@ namespace Server.Models
{ {
int bytesReceived = this.stream.EndRead(ar); int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024) if (totalBufferReceived + bytesReceived > 2048)
{ {
throw new OutOfMemoryException("buffer is too small!"); throw new OutOfMemoryException("buffer is too small!");
} }
// copy the received bytes into the buffer // copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount // add the bytes we received to the total amount
@@ -90,6 +91,7 @@ namespace Server.Models
} }
ar.AsyncWaitHandle.WaitOne(); ar.AsyncWaitHandle.WaitOne();
// 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);
@@ -154,48 +156,47 @@ namespace Server.Models
break; break;
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
Debug.WriteLine("[SERVERCLIENT] GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
CanvasInfo typeToCheck = JSONConvert.GetCanvasMessageType(payload); int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
switch (typeToCheck) switch (typeToCheck)
{ {
case CanvasInfo.DRAWING: case JSONConvert.CANVAS_WRITING:
dynamic canvasData = new dynamic canvasData = new
{ {
type = JSONConvert.GetCanvasMessageType(payload), canvasType = typeToCheck,
coordinatesLine = JSONConvert.getCoordinates(payload), coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(payload) color = JSONConvert.getCanvasDrawingColor(payload)
}; };
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasData)); serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
break; break;
case CanvasInfo.RESET: case JSONConvert.CANVAS_RESET:
dynamic canvasDataForReset = new dynamic canvasDataForReset = new
{ {
type = JSONConvert.GetCanvasMessageType(payload) type = JSONConvert.GetCanvasMessageType(payload)
}; };
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasDataForReset)); serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasDataForReset));
break; break;
} }
// 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;
case JSONConvert.GAME: case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic"); Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload); string command = JSONConvert.GetGameCommand(payload);
switch (command) switch (command)
{ {
case "startGame": case "startGame":
int lobbyID = JSONConvert.GetStartGameLobbyID(payload); int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID); serverCom.CloseALobby(lobbyID);
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break; break;
} }
break; break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
break; break;
@@ -203,6 +204,7 @@ namespace Server.Models
// we now can send a new message // we now can send a new message
OnMessageReceivedOk?.Invoke(); OnMessageReceivedOk?.Invoke();
break; break;
default: default:
Debug.WriteLine("[SERVER] Received weird identifier: " + id); Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break; break;
@@ -232,6 +234,7 @@ namespace Server.Models
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () => OnMessageReceivedOk = () =>
{ {
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{ {
id = serverCom.GetLobbyForUser(User).ID, id = serverCom.GetLobbyForUser(User).ID,

View File

@@ -1,5 +1,4 @@
using Client; using Client;
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
@@ -8,8 +7,8 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Media; using System.Windows.Media;
namespace SharedClientServer namespace SharedClientServer
{ {
class JSONConvert class JSONConvert
@@ -20,9 +19,12 @@ namespace SharedClientServer
public const byte CANVAS = 0x04; public const byte CANVAS = 0x04;
public const byte GAME = 0x05; public const byte GAME = 0x05;
public const byte MESSAGE_RECEIVED = 0x06; public const byte MESSAGE_RECEIVED = 0x06;
public const byte RANDOMWORD = 0x07; public const byte RANDOMWORD = 0x07;
public const int CANVAS_WRITING = 0;
public const int CANVAS_RESET = 1;
public enum LobbyIdentifier public enum LobbyIdentifier
{ {
HOST, HOST,
@@ -33,15 +35,9 @@ namespace SharedClientServer
REQUEST REQUEST
} }
public enum CanvasInfo
{
DRAWING,
RESET
}
public static (string,string) GetUsernameAndMessage(byte[] json) public static (string,string) GetUsernameAndMessage(byte[] json)
{ {
string msg = Encoding.ASCII.GetString(json); string msg = Encoding.UTF8.GetString(json);
dynamic payload = JsonConvert.DeserializeObject(msg); dynamic payload = JsonConvert.DeserializeObject(msg);
return (payload.username, payload.message); return (payload.username, payload.message);
@@ -49,7 +45,7 @@ namespace SharedClientServer
public static string GetUsernameLogin(byte[] json) public static string GetUsernameLogin(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.username; return payload.username;
} }
@@ -117,13 +113,13 @@ namespace SharedClientServer
} }
public static LobbyIdentifier GetLobbyIdentifier(byte[] json) public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.identifier; return payload.identifier;
} }
public static Lobby[] GetLobbiesFromMessage(byte[] json) public static Lobby[] GetLobbiesFromMessage(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JArray lobbiesArray = payload.lobbies; JArray lobbiesArray = payload.lobbies;
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString()); Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>(); Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
@@ -137,13 +133,13 @@ namespace SharedClientServer
public static int GetLobbyID(byte[] json) public static int GetLobbyID(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.id; return payload.id;
} }
public static Lobby GetLobby(byte[] json) public static Lobby GetLobby(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JObject dynamicAsObject = payload.lobby; JObject dynamicAsObject = payload.lobby;
return dynamicAsObject.ToObject<Lobby>(); return dynamicAsObject.ToObject<Lobby>();
} }
@@ -156,44 +152,55 @@ namespace SharedClientServer
public static bool GetLobbyJoinIsHost(byte[] json) public static bool GetLobbyJoinIsHost(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.host; return payload.host;
} }
#endregion #endregion
public static byte[] ConstructCanvasDataSend(CanvasInfo typeToSend, double[] coordinates, Color colorToSend) public static byte[] ConstructCanvasDataSend(int typeToSend, double[][] buffer, Color colorToSend)
{ {
return GetMessageToSend(CANVAS, new return GetMessageToSend(CANVAS, new
{ {
type = typeToSend, canvasType = typeToSend,
coordinatesLine = coordinates, coords = buffer,
color = colorToSend color = colorToSend
}); ; }); ;
} }
public static CanvasInfo GetCanvasMessageType(byte[] payload) public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payload)); return GetMessageToSend(CANVAS, new
CanvasInfo type = json.type; {
return type; canvasType = CANVAS_WRITING,
coords = buffer,
color = colorToSend
});
} }
public static double[] getCoordinates(byte[] payload) public static int GetCanvasMessageType(byte[] json)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payload)); dynamic d = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JArray coordinatesArray = json.coordinatesLine; return d.canvasType;
}
double[] coordinates = coordinatesArray.ToObject<double[]>(); public static double[][] getCoordinates(byte[] payload)
{
Debug.WriteLine("got coords " + Encoding.UTF8.GetString(payload));
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
JArray coordinatesArray = json.coords;
double[][] coordinates = coordinatesArray.ToObject<double[][]>();
return coordinates; return coordinates;
} }
public static Color getCanvasDrawingColor(byte[] payload) public static Color getCanvasDrawingColor(byte[] payload)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payload)); dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
Color color = json.color; Color color = json.color;
return color; return color;
} }
public static byte[] ConstructGameStartData(int lobbyID) public static byte[] ConstructGameStartData(int lobbyID)
@@ -208,13 +215,13 @@ namespace SharedClientServer
public static string GetGameCommand(byte[] payload) public static string GetGameCommand(byte[] payload)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payload)); dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command; return json.command;
} }
public static int GetStartGameLobbyID(byte[] payload) public static int GetStartGameLobbyID(byte[] payload)
{ {
dynamic json = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(payload)); dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.lobbyToStart; return json.lobbyToStart;
} }
@@ -227,7 +234,8 @@ namespace SharedClientServer
public static byte[] GetMessageToSend(byte identifier, dynamic payload) public static byte[] GetMessageToSend(byte identifier, dynamic payload)
{ {
// convert the dynamic to bytes // convert the dynamic to bytes
byte[] payloadBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload)); string json = JsonConvert.SerializeObject(payload);
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
// make the array that holds the message and copy the payload into it with the first spot containing the identifier // make the array that holds the message and copy the payload into it with the first spot containing the identifier
byte[] res = new byte[payloadBytes.Length + 5]; byte[] res = new byte[payloadBytes.Length + 5];
// put the payload in the res array // put the payload in the res array
@@ -238,8 +246,8 @@ namespace SharedClientServer
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4); Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4);
return res; return res;
} }
/* /*
* This method sends a random word from the json file, this happens when the client joins a lobby. * This method sends a random word from the json file, this happens when the client joins a lobby.
*/ */
public static string SendRandomWord(string filename) public static string SendRandomWord(string filename)
@@ -272,5 +280,7 @@ namespace SharedClientServer
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
return payload.word; return payload.word;
} }
} }
} }

View File

@@ -6,7 +6,7 @@ using System.Text;
namespace Client namespace Client
{ {
class Lobby : INotifyPropertyChanged internal class Lobby : INotifyPropertyChanged
{ {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;