18 Commits

Author SHA1 Message Date
SemvdH
0158841159 Merge branch 'master' into stateful-canvas 2020-10-22 22:30:42 +02:00
Sem van der Hoeven
8a490eb399 [FIX] AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2020-10-22 22:22:24 +02:00
Sem van der Hoeven
5e408091cb the fuck????? 2020-10-22 22:04:20 +02:00
Lars
eae05d17df [ADDED] Color can now we transfered, still need to get fixed with the buffer -_- 2020-10-22 17:30:40 +02:00
Sem van der Hoeven
d37696d4bd [FIX] made message sending statful 2020-10-22 17:11:55 +02:00
Sem van der Hoeven
4a400628df [FIX] merge stuff 2020-10-22 17:05:02 +02:00
SemvdH
9fa231ab00 Merge pull request #7 from SemvdH/fix-async-stuff
merge Fix async stuff into master
2020-10-22 17:02:30 +02:00
SemvdH
21ee724056 Merge pull request #6 from SemvdH/feature/jsonForWords
Feature/json for words
2020-10-22 17:01:41 +02:00
Sem van der Hoeven
eca17cc70f [FIX] handled disconnects for everything 2020-10-22 17:00:26 +02:00
Sem van der Hoeven
07b0357b0a Merge branch 'feature/jsonForWords' into fix-async-stuff 2020-10-22 16:37:05 +02:00
Sem van der Hoeven
d8bbaf5258 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:36:45 +02:00
Sem van der Hoeven
bb289865b7 [ADD] added message received ok 2020-10-22 16:34:31 +02:00
Sem van der Hoeven
f1878eaf25 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:16:08 +02:00
Lars
1fdba622cc Merge branch 'master' into setupBranch 2020-10-22 15:46:20 +02:00
Lars
cac0fdc0a4 [ADDED] lobby now secured when the game starts. start button is still for everyone available, not working yet 2020-10-22 15:40:09 +02:00
Sem van der Hoeven
674c4f1ba1 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 13:55:49 +02:00
Sem van der Hoeven
d3bd1418d1 line 2020-10-22 13:55:46 +02:00
Lars
8190724f77 [ADDED] canvas data sending to the server works, but not fully yet to all the clients 2020-10-21 23:18:37 +02:00
13 changed files with 559 additions and 216 deletions

View File

@@ -2,20 +2,29 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows.Media;
using System.Windows;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyCallback(int id);
public delegate void LobbyJoinCallback(bool isHost); public delegate void LobbyJoinCallback(bool isHost);
public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset();
public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
private ClientData clientData = ClientData.Instance;
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public int Port = 5555; public int Port = 5555;
public bool Connected = false; public bool Connected = false;
@@ -24,9 +33,12 @@ namespace Client
public Callback OnLobbiesListReceived; public Callback OnLobbiesListReceived;
public LobbyJoinCallback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect;
public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave; public LobbyCallback OnLobbyLeave;
private ClientData data = ClientData.Instance; private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset;
public Lobby[] Lobbies { get; set; } public Lobby[] Lobbies { get; set; }
public Client(string username) public Client(string username)
@@ -40,45 +52,60 @@ namespace Client
private void OnConnect(IAsyncResult ar) private void OnConnect(IAsyncResult ar)
{ {
Debug.Write("finished connecting to server"); Debug.Write("finished connecting to server");
this.tcpClient.EndConnect(ar); try
this.stream = tcpClient.GetStream(); {
OnSuccessfullConnect?.Invoke(); this.tcpClient.EndConnect(ar);
SendMessage(JSONConvert.ConstructUsernameMessage(username)); this.stream = tcpClient.GetStream();
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null); OnSuccessfullConnect?.Invoke();
SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null);
} catch (Exception e)
{
Debug.WriteLine("Can't connect, retrying...");
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
}
} }
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
int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 1024)
{ {
throw new OutOfMemoryException("buffer too small"); int amountReceived = stream.EndRead(ar);
}
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived); if (totalBufferReceived + amountReceived > 2048)
totalBufferReceived += amountReceived; {
throw new OutOfMemoryException("buffer too small");
}
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength) Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived;
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{
// we have received the complete packet
byte[] message = new byte[expectedMessageLength];
// put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message);
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
}
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (IOException e)
{ {
// we have received the complete packet Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
byte[] message = new byte[expectedMessageLength]; OnServerDisconnect?.Invoke();
// put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message);
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
} }
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
private void handleData(byte[] message) private void handleData(byte[] message)
@@ -142,7 +169,22 @@ namespace Client
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
// canvas data // canvas data
break; //clientData.CanvasData = JSONConvert.getCoordinates(payload);
int type = JSONConvert.GetCanvasMessageType(payload);
switch (type)
{
case JSONConvert.CANVAS_RESET:
CReset?.Invoke();
break;
case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
// we hebben gedrawed, dus stuur dat we weer kunnen drawen
break;
}
break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
@@ -155,6 +197,7 @@ namespace Client
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;
} }
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED,null));
} }
@@ -162,12 +205,14 @@ namespace Client
{ {
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)
{ {
Debug.WriteLine("[CLIENT] finished writing"); Debug.WriteLine("[CLIENT] finished writing");
stream.EndWrite(ar); stream.EndWrite(ar);
stream.Flush();
} }
} }
} }

View File

@@ -31,6 +31,7 @@ namespace Client
private Client _client; private Client _client;
private Lobby _lobby; private Lobby _lobby;
private string _message; private string _message;
private double[] _canvasData = new double[4];
private ClientData() private ClientData()
{ {
@@ -68,5 +69,11 @@ namespace Client
} }
} }
public double[] CanvasData
{
get { return _canvasData; }
set { _canvasData = value; }
}
} }
} }

View File

@@ -11,6 +11,9 @@ 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.Windows.Controls.Primitives;
using System.Windows.Controls;
namespace Client namespace Client
{ {
@@ -35,6 +38,10 @@ namespace Client
client = ClientData.Instance.Client; client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies; client.OnLobbiesListReceived = updateLobbies;
client.OnLobbyLeave = leaveLobby; client.OnLobbyLeave = leaveLobby;
client.OnServerDisconnect = () =>
{
Environment.Exit(0);
};
OnHostButtonClick = new RelayCommand(hostGame); OnHostButtonClick = new RelayCommand(hostGame);
@@ -58,12 +65,10 @@ namespace Client
private void becomeHostForLobby(int id) private void becomeHostForLobby(int id)
{ {
Debug.WriteLine($"got host succes with data {id} "); Debug.WriteLine($"got host succes with data {id} ");
wantToBeHost = true; wantToBeHost = true;
wantToBeHostId = id; wantToBeHostId = id;
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived; client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
} }
private void hostLobbiesReceived() private void hostLobbiesReceived()
@@ -85,9 +90,16 @@ namespace Client
private void joinLobby() private void joinLobby()
{ {
if (SelectedLobby != null)
{
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
{
return;
}
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
}
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
} }
private void OnLobbyJoinSuccess(bool isHost) private void OnLobbyJoinSuccess(bool isHost)
@@ -163,5 +175,7 @@ namespace Client
get { return _lobbies; } get { return _lobbies; }
set { _lobbies = value; } set { _lobbies = value; }
} }
} }
} }

View File

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

View File

@@ -34,12 +34,27 @@
</Grid> </Grid>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/> <Grid Grid.Row="0" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<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"/>
<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"/>
</Grid>
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="140,0,109,0"/> <Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="140,0,109,0"/>
<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"/>
<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">
<Canvas.Background> <Canvas.Background>

View File

@@ -15,7 +15,7 @@ namespace Client.Views
private ViewModelGame viewModel; private ViewModelGame viewModel;
public GameWindow() public GameWindow()
{ {
this.viewModel = new ViewModelGame(); this.viewModel = new ViewModelGame(this);
DataContext = this.viewModel; DataContext = this.viewModel;
Closing += this.viewModel.LeaveGame; Closing += this.viewModel.LeaveGame;
InitializeComponent(); InitializeComponent();

View File

@@ -57,7 +57,8 @@
<GridView x:Name="grdList"> <GridView x:Name="grdList">
<GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/> <GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/>
<GridViewColumn Header="Players in" DisplayMemberBinding="{Binding PlayersIn}" Width="70"/> <GridViewColumn Header="Players in" DisplayMemberBinding="{Binding PlayersIn}" Width="70"/>
<GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}"/> <GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}" Width="150"/>
<GridViewColumn Header="joinable" DisplayMemberBinding="{Binding LobbyJoinable}"/>
</GridView> </GridView>
</ListView.View> </ListView.View>
</ListView> </ListView>

View File

@@ -15,15 +15,17 @@ using static SharedClientServer.JSONConvert;
namespace Server.Models namespace Server.Models
{ {
public delegate void Callback();
class ServerClient : ObservableObject class ServerClient : ObservableObject
{ {
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public User User { get; set; } public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE; private ServerCommunication serverCom = ServerCommunication.INSTANCE;
private Callback OnMessageReceivedOk;
/// <summary> /// <summary>
@@ -52,7 +54,7 @@ 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!");
} }
@@ -94,6 +96,7 @@ namespace Server.Models
} }
catch (IOException e) catch (IOException e)
{ {
Debug.WriteLine("[SERVERCLIENT] Client disconnected! exception was " + e.Message);
tcpClient.Close(); tcpClient.Close();
ServerCommunication.INSTANCE.ServerClientDisconnect(this); ServerCommunication.INSTANCE.ServerClientDisconnect(this);
} }
@@ -149,15 +152,57 @@ namespace Server.Models
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload); LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
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!!!");
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
switch (typeToCheck)
{
case JSONConvert.CANVAS_WRITING:
dynamic canvasData = new
{
canvasType = typeToCheck,
coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
break;
case JSONConvert.CANVAS_RESET:
dynamic canvasDataForReset = new
{
type = JSONConvert.GetCanvasMessageType(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasDataForReset));
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:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload);
switch (command)
{
case "startGame":
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID);
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
}
break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
break; break;
case JSONConvert.MESSAGE_RECEIVED:
// we now can send a new message
OnMessageReceivedOk?.Invoke();
break;
default: default:
Debug.WriteLine("[SERVER] Received weird identifier: " + id); Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break; break;
@@ -181,21 +226,19 @@ namespace Server.Models
break; break;
case LobbyIdentifier.JOIN: case LobbyIdentifier.JOIN:
int id = JSONConvert.GetLobbyID(payload); int id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.JoinLobby(this.User, id);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
bool isHost; bool isHost;
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost); ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost)); sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () =>
//Task.Run(SendLobbyData);
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{ {
id = serverCom.GetLobbyForUser(User).ID, serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
word = JSONConvert.SendRandomWord("WordsForGame.json") {
})); id = serverCom.GetLobbyForUser(User).ID,
word = JSONConvert.SendRandomWord("WordsForGame.json")
}));
OnMessageReceivedOk = null;
};
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
id = JSONConvert.GetLobbyID(payload); id = JSONConvert.GetLobbyID(payload);

View File

@@ -150,6 +150,21 @@ namespace Server.Models
} }
} }
public void SendCanvasDataToLobby(Lobby lobby, string username, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l == lobby)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
sc.sendMessage(message);
}
break;
}
}
}
public Lobby GetLobbyForUser(User user) public Lobby GetLobbyForUser(User user)
{ {
foreach (Lobby l in lobbies) foreach (Lobby l in lobbies)
@@ -255,5 +270,16 @@ namespace Server.Models
} }
} }
} }
public void CloseALobby(int lobbyID)
{
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobby.LobbyJoinable = false;
}
}
}
} }
} }

View File

@@ -7,6 +7,8 @@ using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
public delegate void Callback(); public delegate void Callback();
class ClientServerUtil class ClientServerUtil
{ {
// creates a message array to send to the server or to clients // creates a message array to send to the server or to clients

View File

@@ -1,13 +1,12 @@
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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Media;
namespace SharedClientServer namespace SharedClientServer
{ {
@@ -17,7 +16,13 @@ namespace SharedClientServer
public const byte MESSAGE = 0x02; public const byte MESSAGE = 0x02;
public const byte LOBBY = 0x03; public const byte LOBBY = 0x03;
public const byte CANVAS = 0x04; public const byte CANVAS = 0x04;
public const byte RANDOMWORD = 0x05; public const byte GAME = 0x05;
public const byte MESSAGE_RECEIVED = 0x06;
public const byte RANDOMWORD = 0x07;
public const int CANVAS_WRITING = 0;
public const int CANVAS_RESET = 1;
public enum LobbyIdentifier public enum LobbyIdentifier
{ {
@@ -28,9 +33,10 @@ namespace SharedClientServer
LIST, LIST,
REQUEST REQUEST
} }
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);
@@ -38,7 +44,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;
} }
@@ -86,6 +92,7 @@ namespace SharedClientServer
}); });
} }
public static byte[] ConstructLobbyJoinMessage(int lobbyID) public static byte[] ConstructLobbyJoinMessage(int lobbyID)
{ {
return GetMessageToSend(LOBBY, new return GetMessageToSend(LOBBY, new
@@ -105,13 +112,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[]>();
@@ -125,13 +132,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>();
} }
@@ -144,11 +151,79 @@ 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(int typeToSend, double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = typeToSend,
coords = buffer,
color = colorToSend
}); ;
}
public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = CANVAS_WRITING,
coords = buffer,
color = colorToSend
});
}
public static int GetCanvasMessageType(byte[] json)
{
dynamic d = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return d.canvasType;
}
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;
}
public static Color getCanvasDrawingColor(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
Color color = json.color;
return color;
}
public static byte[] ConstructGameStartData(int lobbyID)
{
string startGame = "startGame";
return GetMessageToSend(GAME, new
{
command = startGame,
lobbyToStart = lobbyID
}); ;
}
public static string GetGameCommand(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command;
}
public static int GetStartGameLobbyID(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.lobbyToStart;
}
/// <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>
@@ -158,7 +233,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
@@ -169,8 +245,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)
@@ -203,5 +279,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

@@ -14,6 +14,7 @@ namespace Client
private int _id; private int _id;
private int _playersIn; private int _playersIn;
private int _maxPlayers; private int _maxPlayers;
private bool _lobbyJoinable;
//private List<string> _usernames; //private List<string> _usernames;
private List<User> _users; private List<User> _users;
@@ -34,6 +35,7 @@ namespace Client
_maxPlayers = maxPlayers; _maxPlayers = maxPlayers;
//_usernames = new List<string>(); //_usernames = new List<string>();
_users = new List<User>(); _users = new List<User>();
_lobbyJoinable = true;
} }
public void AddUser(string username, out bool succes) public void AddUser(string username, out bool succes)
@@ -41,7 +43,7 @@ namespace Client
succes = false; succes = false;
if (_users.Count < _maxPlayers) if (_users.Count < _maxPlayers)
{ {
_users.Add(new User(username, 0, false)); _users.Add(new User(username, 0, false, false));
succes = true; succes = true;
} }
} }
@@ -87,6 +89,11 @@ namespace Client
set { _users = value; } set { _users = value; }
} }
public bool LobbyJoinable
{
get { return _lobbyJoinable; }
set { _lobbyJoinable = value; }
}
} }
} }

View File

@@ -11,14 +11,16 @@ namespace SharedClientServer
private string _username; private string _username;
private int _score; private int _score;
private bool _host; private bool _host;
private bool _turnToDraw;
private string _message; private string _message;
[JsonConstructor] [JsonConstructor]
public User(string username, int score, bool host) public User(string username, int score, bool host, bool turnToDraw)
{ {
_username = username; _username = username;
_score = score; _score = score;
_host = host; _host = host;
_turnToDraw = turnToDraw;
} }
public User(string username) public User(string username)
@@ -26,6 +28,7 @@ namespace SharedClientServer
_username = username; _username = username;
_score = 0; _score = 0;
_host = false; _host = false;
_turnToDraw = false;
} }
public static bool operator ==(User u1, User u2) public static bool operator ==(User u1, User u2)
@@ -81,5 +84,11 @@ namespace SharedClientServer
get { return _host; } get { return _host; }
set { _host = value; } set { _host = value; }
} }
public bool TurnToDraw
{
get { return _turnToDraw; }
set { _turnToDraw = value; }
}
} }
} }