Merge branch 'master' into stateful-canvas
This commit is contained in:
111
Client/Client.cs
111
Client/Client.cs
@@ -2,9 +2,12 @@
|
|||||||
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.Media;
|
||||||
|
using System.Windows;
|
||||||
|
|
||||||
using static SharedClientServer.JSONConvert;
|
using static SharedClientServer.JSONConvert;
|
||||||
|
|
||||||
namespace Client
|
namespace Client
|
||||||
@@ -30,6 +33,7 @@ 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;
|
||||||
@@ -48,43 +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)
|
||||||
{
|
{
|
||||||
int amountReceived = stream.EndRead(ar);
|
|
||||||
if (totalBufferReceived + amountReceived > 2048)
|
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
|
||||||
|
return;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
throw new OutOfMemoryException("buffer too small");
|
int amountReceived = stream.EndRead(ar);
|
||||||
}
|
|
||||||
|
|
||||||
// copy the received bytes into the buffer
|
|
||||||
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
|
|
||||||
// add the bytes we received to the total amount
|
|
||||||
totalBufferReceived += amountReceived;
|
|
||||||
|
|
||||||
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
if (totalBufferReceived + amountReceived > 2048)
|
||||||
|
{
|
||||||
|
throw new OutOfMemoryException("buffer too small");
|
||||||
|
}
|
||||||
|
|
||||||
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;
|
|
||||||
Debug.WriteLine($"reduced buffer: {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)
|
||||||
@@ -150,25 +171,33 @@ namespace Client
|
|||||||
// canvas data
|
// canvas data
|
||||||
//clientData.CanvasData = JSONConvert.getCoordinates(payload);
|
//clientData.CanvasData = JSONConvert.getCoordinates(payload);
|
||||||
int type = JSONConvert.GetCanvasMessageType(payload);
|
int type = JSONConvert.GetCanvasMessageType(payload);
|
||||||
switch (type)
|
switch (type)
|
||||||
{
|
{
|
||||||
case JSONConvert.CANVAS_RESET:
|
case JSONConvert.CANVAS_RESET:
|
||||||
CReset?.Invoke();
|
CReset?.Invoke();
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.CANVAS_WRITING:
|
case JSONConvert.CANVAS_WRITING:
|
||||||
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
|
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
|
||||||
// we hebben gedrawed, dus stuur dat we weer kunnen drawen
|
// we hebben gedrawed, dus stuur dat we weer kunnen drawen
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|
||||||
|
case JSONConvert.RANDOMWORD:
|
||||||
|
//Flag byte for receiving the random word.
|
||||||
|
int lobbyId = JSONConvert.GetLobbyID(payload);
|
||||||
|
|
||||||
|
if(data.Lobby?.ID == lobbyId)
|
||||||
|
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload));
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
|
Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED,null));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -38,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);
|
||||||
@@ -61,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()
|
||||||
@@ -88,16 +90,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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,225 +1,244 @@
|
|||||||
|
|
||||||
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.Generic;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.ObjectModel;
|
||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Timers;
|
using System.Timers;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Input;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Media;
|
using System.Windows.Input;
|
||||||
using System.Windows.Shapes;
|
using System.Windows.Media;
|
||||||
|
using System.Windows.Shapes;
|
||||||
namespace Client.ViewModels
|
|
||||||
{
|
namespace Client.ViewModels
|
||||||
class ViewModelGame : INotifyPropertyChanged
|
{
|
||||||
{
|
class ViewModelGame : INotifyPropertyChanged
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
{
|
||||||
private ClientData data = ClientData.Instance;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
private GameWindow window;
|
private ClientData data = ClientData.Instance;
|
||||||
private Point currentPoint = new Point();
|
private GameWindow window;
|
||||||
public Color color;
|
private Point currentPoint = new Point();
|
||||||
public double[][] buffer;
|
public Color color;
|
||||||
public int pos = 0;
|
public double[][] buffer;
|
||||||
public int maxLines = 50;
|
public int pos = 0;
|
||||||
public Queue<double[][]> linesQueue;
|
public int maxLines = 50;
|
||||||
private Timer queueTimer;
|
public Queue<double[][]> linesQueue;
|
||||||
|
private Timer queueTimer;
|
||||||
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
|
||||||
|
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
||||||
private dynamic _payload;
|
|
||||||
|
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
|
||||||
}
|
{
|
||||||
|
return _message;
|
||||||
public bool IsHost
|
}
|
||||||
{
|
set
|
||||||
get { return data.User.Host; }
|
{
|
||||||
}
|
_message = value;
|
||||||
|
}
|
||||||
public ViewModelGame(GameWindow window)
|
}
|
||||||
{
|
|
||||||
this.window = window;
|
public bool IsHost
|
||||||
if (_payload == null)
|
{
|
||||||
{
|
get { return data.User.Host; }
|
||||||
_message = "";
|
}
|
||||||
|
|
||||||
}
|
public ViewModelGame(GameWindow window)
|
||||||
else
|
{
|
||||||
{
|
this.window = window;
|
||||||
//_message = data.Message;
|
if (_payload == null)
|
||||||
//_username = data.User.Username;
|
{
|
||||||
//Messages.Add($"{data.User.Username}: {Message}");
|
_message = "";
|
||||||
}
|
|
||||||
|
}
|
||||||
buffer = new double[maxLines][];
|
else
|
||||||
linesQueue = new Queue<double[][]>();
|
{
|
||||||
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
//_message = data.Message;
|
||||||
ButtonStartGame = new RelayCommand(BeginGame);
|
//_username = data.User.Username;
|
||||||
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
|
//Messages.Add($"{data.User.Username}: {Message}");
|
||||||
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
|
}
|
||||||
data.Client.CReset = CanvasResetData;
|
|
||||||
}
|
buffer = new double[maxLines][];
|
||||||
|
linesQueue = new Queue<double[][]>();
|
||||||
public ICommand OnKeyDown { get; set; }
|
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
||||||
public ICommand ButtonStartGame { get; set; }
|
ButtonStartGame = new RelayCommand(BeginGame);
|
||||||
public ICommand ButtonResetCanvas { get; set; }
|
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
|
||||||
|
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
|
||||||
public void BeginGame()
|
data.Client.CReset = CanvasResetData;
|
||||||
{
|
}
|
||||||
|
|
||||||
queueTimer = new Timer(50);
|
public ICommand OnKeyDown { get; set; }
|
||||||
queueTimer.Start();
|
public ICommand ButtonStartGame { get; set; }
|
||||||
queueTimer.Elapsed += sendArrayFromQueue;
|
public ICommand ButtonResetCanvas { get; set; }
|
||||||
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
|
||||||
}
|
public void BeginGame()
|
||||||
|
{
|
||||||
|
|
||||||
private void CanvasResetLocal()
|
queueTimer = new Timer(50);
|
||||||
{
|
queueTimer.Start();
|
||||||
this.window.CanvasForPaint.Children.Clear();
|
queueTimer.Elapsed += sendArrayFromQueue;
|
||||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
|
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
private void CanvasResetLocal()
|
||||||
{
|
{
|
||||||
if (e.ButtonState == MouseButtonState.Pressed)
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
{
|
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
|
||||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
||||||
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
{
|
||||||
{
|
if (e.ButtonState == MouseButtonState.Pressed)
|
||||||
if (e.LeftButton == MouseButtonState.Pressed)
|
{
|
||||||
{
|
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||||
double[] coordinates = new double[4];
|
}
|
||||||
Line line = new Line();
|
}
|
||||||
|
|
||||||
line.Stroke = new SolidColorBrush(color);
|
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
||||||
//line.Stroke = SystemColors.WindowFrameBrush;
|
{
|
||||||
line.X1 = currentPoint.X;
|
if (e.LeftButton == MouseButtonState.Pressed)
|
||||||
line.Y1 = currentPoint.Y;
|
{
|
||||||
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
double[] coordinates = new double[4];
|
||||||
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
Line line = new Line();
|
||||||
coordinates[0] = line.X1;
|
|
||||||
coordinates[1] = line.Y1;
|
line.Stroke = new SolidColorBrush(color);
|
||||||
coordinates[2] = line.X2;
|
//line.Stroke = SystemColors.WindowFrameBrush;
|
||||||
coordinates[3] = line.Y2;
|
line.X1 = currentPoint.X;
|
||||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
line.Y1 = currentPoint.Y;
|
||||||
buffer[pos] = coordinates;
|
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
||||||
pos++;
|
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
||||||
|
coordinates[0] = line.X1;
|
||||||
window.CanvasForPaint.Children.Add(line);
|
coordinates[1] = line.Y1;
|
||||||
if (pos == maxLines)
|
coordinates[2] = line.X2;
|
||||||
{
|
coordinates[3] = line.Y2;
|
||||||
double[][] temp = new double[maxLines][];
|
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||||
for (int i = 0; i < maxLines; i++)
|
buffer[pos] = coordinates;
|
||||||
{
|
pos++;
|
||||||
temp[i] = buffer[i];
|
|
||||||
}
|
window.CanvasForPaint.Children.Add(line);
|
||||||
linesQueue.Enqueue(temp);
|
if (pos == maxLines)
|
||||||
Array.Clear(buffer, 0, buffer.Length);
|
{
|
||||||
pos = 0;
|
double[][] temp = new double[maxLines][];
|
||||||
}
|
for (int i = 0; i < maxLines; i++)
|
||||||
|
{
|
||||||
}
|
temp[i] = buffer[i];
|
||||||
}
|
}
|
||||||
|
linesQueue.Enqueue(temp);
|
||||||
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
|
Array.Clear(buffer, 0, buffer.Length);
|
||||||
{
|
pos = 0;
|
||||||
|
}
|
||||||
if (linesQueue.Count != 0)
|
|
||||||
{
|
}
|
||||||
Debug.WriteLine("[GAME] sending canvas data...");
|
}
|
||||||
double[][] temp = linesQueue.Dequeue();
|
|
||||||
data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
|
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
|
||||||
}
|
{
|
||||||
}
|
|
||||||
|
if (linesQueue.Count != 0)
|
||||||
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
|
{
|
||||||
{
|
Debug.WriteLine("[GAME] sending canvas data...");
|
||||||
Color colorSelected = new Color();
|
double[][] temp = linesQueue.Dequeue();
|
||||||
colorSelected.A = 255;
|
data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
|
||||||
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 void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
|
||||||
}
|
{
|
||||||
|
Color colorSelected = new Color();
|
||||||
private void UpdateCanvasWithNewData(double[][] buffer, Color color)
|
colorSelected.A = 255;
|
||||||
{
|
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
|
||||||
Application.Current.Dispatcher.Invoke(delegate
|
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
|
||||||
{
|
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
|
||||||
foreach (double[] arr in buffer)
|
color = colorSelected;
|
||||||
{
|
}
|
||||||
Line line = new Line();
|
|
||||||
line.Stroke = new SolidColorBrush(color);
|
private void UpdateCanvasWithNewData(double[][] buffer, Color color)
|
||||||
line.X1 = arr[0];
|
{
|
||||||
line.Y1 = arr[1];
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
line.X2 = arr[2];
|
{
|
||||||
line.Y2 = arr[3];
|
foreach (double[] arr in buffer)
|
||||||
this.window.CanvasForPaint.Children.Add(line);
|
{
|
||||||
}
|
Line line = new Line();
|
||||||
});
|
line.Stroke = new SolidColorBrush(color);
|
||||||
}
|
line.X1 = arr[0];
|
||||||
|
line.Y1 = arr[1];
|
||||||
private void CanvasResetData()
|
line.X2 = arr[2];
|
||||||
{
|
line.Y2 = arr[3];
|
||||||
this.window.CanvasForPaint.Children.Clear();
|
this.window.CanvasForPaint.Children.Add(line);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
private void ChatBox_KeyDown()
|
}
|
||||||
{
|
|
||||||
//if enter then clear textbox and send message.
|
private void CanvasResetData()
|
||||||
if (Message != string.Empty) AddMessage(Message);
|
{
|
||||||
Message = string.Empty;
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void AddMessage(string message)
|
private void ChatBox_KeyDown()
|
||||||
{
|
{
|
||||||
Messages.Add($"{data.User.Username}: {message}");
|
//if enter then clear textbox and send message.
|
||||||
|
if (Message != string.Empty) AddMessage(Message);
|
||||||
_payload = new
|
Message = string.Empty;
|
||||||
{
|
}
|
||||||
username = data.User.Username,
|
|
||||||
message = message
|
internal void AddMessage(string message)
|
||||||
};
|
{
|
||||||
|
Messages.Add($"{data.User.Username}: {message}");
|
||||||
//Broadcast the message after adding it to the list!
|
|
||||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
|
_payload = new
|
||||||
}
|
{
|
||||||
|
username = data.User.Username,
|
||||||
public static void HandleIncomingMsg(string username, string message)
|
message = message
|
||||||
{
|
};
|
||||||
Application.Current.Dispatcher.Invoke(delegate
|
|
||||||
{
|
//Broadcast the message after adding it to the list!
|
||||||
Messages.Add($"{username}: {message}");
|
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
|
||||||
});
|
}
|
||||||
}
|
|
||||||
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
|
/*
|
||||||
{
|
* MISC make this a callback
|
||||||
Debug.WriteLine("Leaving...");
|
* Handles the incoming chat message from another client.
|
||||||
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
|
*/
|
||||||
}
|
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";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,6 +50,9 @@
|
|||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
|
<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"/>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
|||||||
@@ -9,10 +9,13 @@ 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.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using static SharedClientServer.JSONConvert;
|
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;
|
||||||
@@ -22,7 +25,8 @@ namespace Server.Models
|
|||||||
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>
|
||||||
/// Constructor that creates a new serverclient object with the given tcp client.
|
/// Constructor that creates a new serverclient object with the given tcp client.
|
||||||
@@ -86,17 +90,18 @@ namespace Server.Models
|
|||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
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);
|
||||||
|
|
||||||
}
|
}
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -108,21 +113,21 @@ namespace Server.Models
|
|||||||
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
|
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(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("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
|
Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
|
||||||
switch(id)
|
switch (id)
|
||||||
{
|
{
|
||||||
|
|
||||||
case JSONConvert.LOGIN:
|
case JSONConvert.LOGIN:
|
||||||
// json log in username data
|
// json log in username data
|
||||||
string uName = JSONConvert.GetUsernameLogin(payload);
|
string uName = JSONConvert.GetUsernameLogin(payload);
|
||||||
|
|
||||||
if (uName != null)
|
if (uName != null)
|
||||||
{
|
{
|
||||||
User = new User(uName);
|
User = new User(uName);
|
||||||
User.Username = uName;
|
User.Username = uName;
|
||||||
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
|
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
|
||||||
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case JSONConvert.MESSAGE:
|
case JSONConvert.MESSAGE:
|
||||||
@@ -145,51 +150,58 @@ namespace Server.Models
|
|||||||
case JSONConvert.LOBBY:
|
case JSONConvert.LOBBY:
|
||||||
// lobby data
|
// lobby data
|
||||||
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
||||||
handleLobbyMessage(payload,l);
|
handleLobbyMessage(payload, l);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.CANVAS:
|
case JSONConvert.CANVAS:
|
||||||
|
|
||||||
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
|
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
|
||||||
switch (typeToCheck)
|
switch (typeToCheck)
|
||||||
{
|
{
|
||||||
case JSONConvert.CANVAS_WRITING:
|
case JSONConvert.CANVAS_WRITING:
|
||||||
dynamic canvasData = new
|
dynamic canvasData = new
|
||||||
{
|
{
|
||||||
canvasType = typeToCheck,
|
canvasType = typeToCheck,
|
||||||
coords = JSONConvert.getCoordinates(payload),
|
coords = JSONConvert.getCoordinates(payload),
|
||||||
color = JSONConvert.getCanvasDrawingColor(payload)
|
color = JSONConvert.getCanvasDrawingColor(payload)
|
||||||
};
|
};
|
||||||
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
|
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.CANVAS_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:
|
||||||
|
//Flag byte for receiving the random word.
|
||||||
|
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);
|
||||||
@@ -218,6 +230,15 @@ namespace Server.Models
|
|||||||
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 = () =>
|
||||||
|
{
|
||||||
|
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
|
||||||
|
{
|
||||||
|
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);
|
||||||
@@ -228,6 +249,21 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async void SendLobbyData()
|
||||||
|
{
|
||||||
|
string result = await WaitForData();
|
||||||
|
if(result == "bruh momento")
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> WaitForData()
|
||||||
|
{
|
||||||
|
await Task.Delay(1000);
|
||||||
|
return "bruh momento";
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// sends a message to the tcp client
|
/// sends a message to the tcp client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ namespace Server.Models
|
|||||||
/// send a message to all tcp clients in the list
|
/// send a message to all tcp clients in the list
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="message">the message to send</param>
|
/// <param name="message">the message to send</param>
|
||||||
public void sendToAll(byte[] message)
|
public async void sendToAll(byte[] message)
|
||||||
{
|
{
|
||||||
foreach (ServerClient sc in serverClients)
|
foreach (ServerClient sc in serverClients)
|
||||||
{
|
{
|
||||||
@@ -142,6 +142,7 @@ namespace Server.Models
|
|||||||
{
|
{
|
||||||
foreach (ServerClient sc in serverClientsInlobbies[l])
|
foreach (ServerClient sc in serverClientsInlobbies[l])
|
||||||
{
|
{
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] Sending message");
|
||||||
sc.sendMessage(message);
|
sc.sendMessage(message);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -6,6 +6,16 @@
|
|||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="resources\WordsForGame.json" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Include="resources\WordsForGame.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
|
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
|
||||||
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />
|
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />
|
||||||
|
|||||||
31
Server/resources/WordsForGame.json
Normal file
31
Server/resources/WordsForGame.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"filename": "wordsForGame",
|
||||||
|
"words": [
|
||||||
|
"teacher",
|
||||||
|
"love",
|
||||||
|
"engineer",
|
||||||
|
"supermarket",
|
||||||
|
"disaster",
|
||||||
|
"studio",
|
||||||
|
"restaurant",
|
||||||
|
"music",
|
||||||
|
"chocolate",
|
||||||
|
"dirt",
|
||||||
|
"thought",
|
||||||
|
"virus",
|
||||||
|
"lieutenant",
|
||||||
|
"painter",
|
||||||
|
"kiwi",
|
||||||
|
"power ranger",
|
||||||
|
"computer",
|
||||||
|
"people",
|
||||||
|
"candidate",
|
||||||
|
"security guard",
|
||||||
|
"Canada",
|
||||||
|
"teeth",
|
||||||
|
"army",
|
||||||
|
"airport",
|
||||||
|
"president",
|
||||||
|
"bedroom"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,249 +1,285 @@
|
|||||||
using Client;
|
using Client;
|
||||||
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.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
|
||||||
{
|
{
|
||||||
public const byte LOGIN = 0x01;
|
public const byte LOGIN = 0x01;
|
||||||
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 GAME = 0x05;
|
public const byte GAME = 0x05;
|
||||||
|
public const byte MESSAGE_RECEIVED = 0x06;
|
||||||
public const int CANVAS_WRITING = 0;
|
public const byte RANDOMWORD = 0x07;
|
||||||
public const int CANVAS_RESET = 1;
|
|
||||||
|
public const int CANVAS_WRITING = 0;
|
||||||
|
public const int CANVAS_RESET = 1;
|
||||||
public enum LobbyIdentifier
|
|
||||||
{
|
|
||||||
HOST,
|
public enum LobbyIdentifier
|
||||||
JOIN,
|
{
|
||||||
JOIN_SUCCESS,
|
HOST,
|
||||||
LEAVE,
|
JOIN,
|
||||||
LIST,
|
JOIN_SUCCESS,
|
||||||
REQUEST
|
LEAVE,
|
||||||
}
|
LIST,
|
||||||
|
REQUEST
|
||||||
public static (string,string) GetUsernameAndMessage(byte[] json)
|
}
|
||||||
{
|
|
||||||
string msg = Encoding.UTF8.GetString(json);
|
public static (string,string) GetUsernameAndMessage(byte[] json)
|
||||||
dynamic payload = JsonConvert.DeserializeObject(msg);
|
{
|
||||||
|
string msg = Encoding.UTF8.GetString(json);
|
||||||
return (payload.username, payload.message);
|
dynamic payload = JsonConvert.DeserializeObject(msg);
|
||||||
}
|
|
||||||
|
return (payload.username, payload.message);
|
||||||
public static string GetUsernameLogin(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static string GetUsernameLogin(byte[] json)
|
||||||
return payload.username;
|
{
|
||||||
}
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.username;
|
||||||
public static byte[] ConstructUsernameMessage(string uName)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOGIN, new
|
public static byte[] ConstructUsernameMessage(string uName)
|
||||||
{
|
{
|
||||||
username = uName
|
return GetMessageToSend(LOGIN, new
|
||||||
});
|
{
|
||||||
}
|
username = uName
|
||||||
|
});
|
||||||
#region lobby messages
|
}
|
||||||
|
|
||||||
public static byte[] ConstructLobbyHostMessage()
|
#region lobby messages
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyHostMessage()
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.HOST
|
return GetMessageToSend(LOBBY, new
|
||||||
});
|
{
|
||||||
}
|
identifier = LobbyIdentifier.HOST
|
||||||
|
});
|
||||||
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.HOST,
|
return GetMessageToSend(LOBBY, new
|
||||||
id = lobbyID
|
{
|
||||||
}) ;
|
identifier = LobbyIdentifier.HOST,
|
||||||
}
|
id = lobbyID
|
||||||
|
}) ;
|
||||||
public static byte[] ConstructLobbyRequestMessage()
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyRequestMessage()
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.REQUEST
|
return GetMessageToSend(LOBBY, new
|
||||||
});
|
{
|
||||||
}
|
identifier = LobbyIdentifier.REQUEST
|
||||||
|
});
|
||||||
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.LIST,
|
return GetMessageToSend(LOBBY, new
|
||||||
lobbies = lobbiesList
|
{
|
||||||
});
|
identifier = LobbyIdentifier.LIST,
|
||||||
}
|
lobbies = lobbiesList
|
||||||
|
});
|
||||||
|
}
|
||||||
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.JOIN,
|
return GetMessageToSend(LOBBY, new
|
||||||
id = lobbyID
|
{
|
||||||
});
|
identifier = LobbyIdentifier.JOIN,
|
||||||
}
|
id = lobbyID
|
||||||
|
});
|
||||||
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new
|
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
|
||||||
{
|
{
|
||||||
identifier = LobbyIdentifier.LEAVE,
|
return GetMessageToSend(LOBBY, new
|
||||||
id = lobbyID
|
{
|
||||||
});
|
identifier = LobbyIdentifier.LEAVE,
|
||||||
}
|
id = lobbyID
|
||||||
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
});
|
||||||
{
|
}
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
||||||
return payload.identifier;
|
{
|
||||||
}
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.identifier;
|
||||||
public static Lobby[] GetLobbiesFromMessage(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static Lobby[] GetLobbiesFromMessage(byte[] json)
|
||||||
JArray lobbiesArray = payload.lobbies;
|
{
|
||||||
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
JArray lobbiesArray = payload.lobbies;
|
||||||
Debug.WriteLine("lobbies in array: ");
|
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
||||||
foreach (Lobby l in lobbiesTemp)
|
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
||||||
{
|
Debug.WriteLine("lobbies in array: ");
|
||||||
Debug.WriteLine("players: " + l.PlayersIn);
|
foreach (Lobby l in lobbiesTemp)
|
||||||
}
|
{
|
||||||
return lobbiesTemp;
|
Debug.WriteLine("players: " + l.PlayersIn);
|
||||||
}
|
}
|
||||||
|
return lobbiesTemp;
|
||||||
public static int GetLobbyID(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static int GetLobbyID(byte[] json)
|
||||||
return payload.id;
|
{
|
||||||
}
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.id;
|
||||||
public static Lobby GetLobby(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static Lobby GetLobby(byte[] json)
|
||||||
JObject dynamicAsObject = payload.lobby;
|
{
|
||||||
return dynamicAsObject.ToObject<Lobby>();
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
}
|
JObject dynamicAsObject = payload.lobby;
|
||||||
|
return dynamicAsObject.ToObject<Lobby>();
|
||||||
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS,
|
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
|
||||||
host = isHost});
|
{
|
||||||
}
|
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS,
|
||||||
|
host = isHost});
|
||||||
public static bool GetLobbyJoinIsHost(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static bool GetLobbyJoinIsHost(byte[] json)
|
||||||
return payload.host;
|
{
|
||||||
}
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.host;
|
||||||
#endregion
|
}
|
||||||
|
|
||||||
public static byte[] ConstructCanvasDataSend(int typeToSend, double[][] buffer, Color colorToSend)
|
#endregion
|
||||||
{
|
|
||||||
|
public static byte[] ConstructCanvasDataSend(int typeToSend, double[][] buffer, Color colorToSend)
|
||||||
return GetMessageToSend(CANVAS, new
|
{
|
||||||
{
|
|
||||||
canvasType = typeToSend,
|
return GetMessageToSend(CANVAS, new
|
||||||
coords = buffer,
|
{
|
||||||
color = colorToSend
|
canvasType = typeToSend,
|
||||||
}); ;
|
coords = buffer,
|
||||||
}
|
color = colorToSend
|
||||||
|
}); ;
|
||||||
public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
|
}
|
||||||
{
|
|
||||||
return GetMessageToSend(CANVAS, new
|
public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
|
||||||
{
|
{
|
||||||
canvasType = CANVAS_WRITING,
|
return GetMessageToSend(CANVAS, new
|
||||||
coords = buffer,
|
{
|
||||||
color = colorToSend
|
canvasType = CANVAS_WRITING,
|
||||||
});
|
coords = buffer,
|
||||||
}
|
color = colorToSend
|
||||||
|
});
|
||||||
public static int GetCanvasMessageType(byte[] json)
|
}
|
||||||
{
|
|
||||||
dynamic d = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
public static int GetCanvasMessageType(byte[] json)
|
||||||
return d.canvasType;
|
{
|
||||||
}
|
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));
|
public static double[][] getCoordinates(byte[] payload)
|
||||||
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
{
|
||||||
JArray coordinatesArray = json.coords;
|
Debug.WriteLine("got coords " + Encoding.UTF8.GetString(payload));
|
||||||
|
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
||||||
double[][] coordinates = coordinatesArray.ToObject<double[][]>();
|
JArray coordinatesArray = json.coords;
|
||||||
|
|
||||||
return coordinates;
|
double[][] coordinates = coordinatesArray.ToObject<double[][]>();
|
||||||
}
|
|
||||||
|
return coordinates;
|
||||||
public static Color getCanvasDrawingColor(byte[] payload)
|
}
|
||||||
{
|
|
||||||
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
public static Color getCanvasDrawingColor(byte[] payload)
|
||||||
Color color = json.color;
|
{
|
||||||
return color;
|
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
||||||
}
|
Color color = json.color;
|
||||||
|
return color;
|
||||||
public static byte[] ConstructGameStartData(int lobbyID)
|
}
|
||||||
{
|
|
||||||
string startGame = "startGame";
|
public static byte[] ConstructGameStartData(int lobbyID)
|
||||||
return GetMessageToSend(GAME, new
|
{
|
||||||
{
|
string startGame = "startGame";
|
||||||
command = startGame,
|
return GetMessageToSend(GAME, new
|
||||||
lobbyToStart = lobbyID
|
{
|
||||||
}); ;
|
command = startGame,
|
||||||
}
|
lobbyToStart = lobbyID
|
||||||
|
}); ;
|
||||||
public static string GetGameCommand(byte[] payload)
|
}
|
||||||
{
|
|
||||||
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
public static string GetGameCommand(byte[] payload)
|
||||||
return json.command;
|
{
|
||||||
}
|
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));
|
public static int GetStartGameLobbyID(byte[] payload)
|
||||||
return json.lobbyToStart;
|
{
|
||||||
}
|
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
||||||
|
return json.lobbyToStart;
|
||||||
/// <summary>
|
}
|
||||||
/// constructs a message that can be sent to the clients or server
|
|
||||||
/// </summary>
|
/// <summary>
|
||||||
/// <param name="identifier">the identifier for what kind of message it is</param>
|
/// constructs a message that can be sent to the clients or server
|
||||||
/// <param name="payload">the json payload</param>
|
/// </summary>
|
||||||
/// <returns>a byte array containing a message that can be sent to clients or server</returns>
|
/// <param name="identifier">the identifier for what kind of message it is</param>
|
||||||
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
|
/// <param name="payload">the json payload</param>
|
||||||
{
|
/// <returns>a byte array containing a message that can be sent to clients or server</returns>
|
||||||
// convert the dynamic to bytes
|
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
|
||||||
string json = JsonConvert.SerializeObject(payload);
|
{
|
||||||
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
|
// convert the dynamic to bytes
|
||||||
// make the array that holds the message and copy the payload into it with the first spot containing the identifier
|
string json = JsonConvert.SerializeObject(payload);
|
||||||
byte[] res = new byte[payloadBytes.Length + 5];
|
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
|
||||||
// put the payload in the res array
|
// make the array that holds the message and copy the payload into it with the first spot containing the identifier
|
||||||
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
|
byte[] res = new byte[payloadBytes.Length + 5];
|
||||||
// put the identifier at the start of the payload part
|
// put the payload in the res array
|
||||||
res[4] = identifier;
|
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
|
||||||
// put the length of the payload at the start of the res array
|
// put the identifier at the start of the payload part
|
||||||
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4);
|
res[4] = identifier;
|
||||||
return res;
|
// put the length of the payload at the start of the res array
|
||||||
}
|
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
}
|
|
||||||
}
|
/*
|
||||||
|
* This method sends a random word from the json file, this happens when the client joins a lobby.
|
||||||
|
*/
|
||||||
|
public static string SendRandomWord(string filename)
|
||||||
|
{
|
||||||
|
dynamic words;
|
||||||
|
Random random = new Random();
|
||||||
|
string workingDir = Path.GetFullPath(@"..\Server");
|
||||||
|
string projDir = Directory.GetParent(workingDir).Parent.Parent.FullName;
|
||||||
|
string filePath = projDir += $@"\resources\{filename}";
|
||||||
|
|
||||||
|
using(StreamReader reader = new StreamReader(filePath))
|
||||||
|
{
|
||||||
|
string json = reader.ReadToEnd();
|
||||||
|
words = JsonConvert.DeserializeObject(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int index = random.Next(0, 24);
|
||||||
|
|
||||||
|
Debug.WriteLine($"[SERVERCLIENT] Sending random words {words}");
|
||||||
|
|
||||||
|
return words.words[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Client gets the payload and retrieves the word from the payload
|
||||||
|
*/
|
||||||
|
public static string GetRandomWord(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
||||||
|
return payload.word;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user