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.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media;
|
||||
using System.Windows;
|
||||
|
||||
using static SharedClientServer.JSONConvert;
|
||||
|
||||
namespace Client
|
||||
@@ -30,6 +33,7 @@ namespace Client
|
||||
public Callback OnLobbiesListReceived;
|
||||
public LobbyJoinCallback OnLobbyJoinSuccess;
|
||||
public Callback OnLobbiesReceivedAndWaitingForHost;
|
||||
public Callback OnServerDisconnect;
|
||||
public LobbyCallback OnLobbyCreated;
|
||||
public LobbyCallback OnLobbyLeave;
|
||||
private ClientData data = ClientData.Instance;
|
||||
@@ -48,43 +52,60 @@ namespace Client
|
||||
private void OnConnect(IAsyncResult ar)
|
||||
{
|
||||
Debug.Write("finished connecting to server");
|
||||
this.tcpClient.EndConnect(ar);
|
||||
this.stream = tcpClient.GetStream();
|
||||
OnSuccessfullConnect?.Invoke();
|
||||
SendMessage(JSONConvert.ConstructUsernameMessage(username));
|
||||
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null);
|
||||
try
|
||||
{
|
||||
this.tcpClient.EndConnect(ar);
|
||||
this.stream = tcpClient.GetStream();
|
||||
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)
|
||||
{
|
||||
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");
|
||||
}
|
||||
|
||||
// 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 amountReceived = stream.EndRead(ar);
|
||||
|
||||
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
|
||||
byte[] message = new byte[expectedMessageLength];
|
||||
// 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);
|
||||
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
|
||||
OnServerDisconnect?.Invoke();
|
||||
}
|
||||
ar.AsyncWaitHandle.WaitOne();
|
||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
|
||||
}
|
||||
|
||||
private void handleData(byte[] message)
|
||||
@@ -150,25 +171,33 @@ namespace Client
|
||||
// canvas data
|
||||
//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;
|
||||
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:
|
||||
//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:
|
||||
Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
|
||||
break;
|
||||
}
|
||||
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED,null));
|
||||
|
||||
}
|
||||
|
||||
@@ -176,12 +205,14 @@ namespace Client
|
||||
{
|
||||
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message));
|
||||
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null);
|
||||
|
||||
}
|
||||
|
||||
private void OnWriteComplete(IAsyncResult ar)
|
||||
{
|
||||
Debug.WriteLine("[CLIENT] finished writing");
|
||||
stream.EndWrite(ar);
|
||||
stream.Flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ using System.Collections.ObjectModel;
|
||||
using Client.Views;
|
||||
using System.Linq;
|
||||
using System.Windows.Data;
|
||||
using System.Data;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Controls;
|
||||
|
||||
using System.Data;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Client
|
||||
{
|
||||
class ViewModel : INotifyPropertyChanged
|
||||
@@ -38,6 +38,10 @@ namespace Client
|
||||
client = ClientData.Instance.Client;
|
||||
client.OnLobbiesListReceived = updateLobbies;
|
||||
client.OnLobbyLeave = leaveLobby;
|
||||
client.OnServerDisconnect = () =>
|
||||
{
|
||||
Environment.Exit(0);
|
||||
};
|
||||
|
||||
|
||||
OnHostButtonClick = new RelayCommand(hostGame);
|
||||
@@ -61,12 +65,10 @@ namespace Client
|
||||
|
||||
private void becomeHostForLobby(int id)
|
||||
{
|
||||
|
||||
Debug.WriteLine($"got host succes with data {id} ");
|
||||
wantToBeHost = true;
|
||||
wantToBeHostId = id;
|
||||
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
|
||||
|
||||
}
|
||||
|
||||
private void hostLobbiesReceived()
|
||||
@@ -88,16 +90,14 @@ namespace Client
|
||||
|
||||
private void joinLobby()
|
||||
{
|
||||
// lobby die je wilt joinen verwijderen
|
||||
// nieuwe binnengekregen lobby toevoegen
|
||||
if (SelectedLobby != null)
|
||||
{
|
||||
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
|
||||
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
|
||||
if (SelectedLobby != null)
|
||||
{
|
||||
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
|
||||
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,225 +1,244 @@
|
||||
|
||||
using Client.Views;
|
||||
using GalaSoft.MvvmLight.Command;
|
||||
using SharedClientServer;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Timers;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace Client.ViewModels
|
||||
{
|
||||
class ViewModelGame : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
private ClientData data = ClientData.Instance;
|
||||
private GameWindow window;
|
||||
private Point currentPoint = new Point();
|
||||
public Color color;
|
||||
public double[][] buffer;
|
||||
public int pos = 0;
|
||||
public int maxLines = 50;
|
||||
public Queue<double[][]> linesQueue;
|
||||
private Timer queueTimer;
|
||||
|
||||
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
||||
|
||||
private dynamic _payload;
|
||||
|
||||
public string _username;
|
||||
|
||||
public string _message;
|
||||
public string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
return _message;
|
||||
}
|
||||
set
|
||||
{
|
||||
_message = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsHost
|
||||
{
|
||||
get { return data.User.Host; }
|
||||
}
|
||||
|
||||
public ViewModelGame(GameWindow window)
|
||||
{
|
||||
this.window = window;
|
||||
if (_payload == null)
|
||||
{
|
||||
_message = "";
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
//_message = data.Message;
|
||||
//_username = data.User.Username;
|
||||
//Messages.Add($"{data.User.Username}: {Message}");
|
||||
}
|
||||
|
||||
buffer = new double[maxLines][];
|
||||
linesQueue = new Queue<double[][]>();
|
||||
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
||||
ButtonStartGame = new RelayCommand(BeginGame);
|
||||
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
|
||||
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
|
||||
data.Client.CReset = CanvasResetData;
|
||||
}
|
||||
|
||||
public ICommand OnKeyDown { get; set; }
|
||||
public ICommand ButtonStartGame { get; set; }
|
||||
public ICommand ButtonResetCanvas { get; set; }
|
||||
|
||||
public void BeginGame()
|
||||
{
|
||||
|
||||
queueTimer = new Timer(50);
|
||||
queueTimer.Start();
|
||||
queueTimer.Elapsed += sendArrayFromQueue;
|
||||
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
||||
}
|
||||
|
||||
|
||||
private void CanvasResetLocal()
|
||||
{
|
||||
this.window.CanvasForPaint.Children.Clear();
|
||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
|
||||
}
|
||||
|
||||
|
||||
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
||||
{
|
||||
if (e.ButtonState == MouseButtonState.Pressed)
|
||||
{
|
||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||
}
|
||||
}
|
||||
|
||||
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
||||
{
|
||||
if (e.LeftButton == MouseButtonState.Pressed)
|
||||
{
|
||||
double[] coordinates = new double[4];
|
||||
Line line = new Line();
|
||||
|
||||
line.Stroke = new SolidColorBrush(color);
|
||||
//line.Stroke = SystemColors.WindowFrameBrush;
|
||||
line.X1 = currentPoint.X;
|
||||
line.Y1 = currentPoint.Y;
|
||||
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
||||
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
||||
coordinates[0] = line.X1;
|
||||
coordinates[1] = line.Y1;
|
||||
coordinates[2] = line.X2;
|
||||
coordinates[3] = line.Y2;
|
||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||
buffer[pos] = coordinates;
|
||||
pos++;
|
||||
|
||||
window.CanvasForPaint.Children.Add(line);
|
||||
if (pos == maxLines)
|
||||
{
|
||||
double[][] temp = new double[maxLines][];
|
||||
for (int i = 0; i < maxLines; i++)
|
||||
{
|
||||
temp[i] = buffer[i];
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
using Client.Views;
|
||||
using GalaSoft.MvvmLight.Command;
|
||||
using SharedClientServer;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Timers;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace Client.ViewModels
|
||||
{
|
||||
class ViewModelGame : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
private ClientData data = ClientData.Instance;
|
||||
private GameWindow window;
|
||||
private Point currentPoint = new Point();
|
||||
public Color color;
|
||||
public double[][] buffer;
|
||||
public int pos = 0;
|
||||
public int maxLines = 50;
|
||||
public Queue<double[][]> linesQueue;
|
||||
private Timer queueTimer;
|
||||
|
||||
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
||||
|
||||
private dynamic _payload;
|
||||
|
||||
public static string Word
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public string _username;
|
||||
|
||||
public string _message;
|
||||
public string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
return _message;
|
||||
}
|
||||
set
|
||||
{
|
||||
_message = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsHost
|
||||
{
|
||||
get { return data.User.Host; }
|
||||
}
|
||||
|
||||
public ViewModelGame(GameWindow window)
|
||||
{
|
||||
this.window = window;
|
||||
if (_payload == null)
|
||||
{
|
||||
_message = "";
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
//_message = data.Message;
|
||||
//_username = data.User.Username;
|
||||
//Messages.Add($"{data.User.Username}: {Message}");
|
||||
}
|
||||
|
||||
buffer = new double[maxLines][];
|
||||
linesQueue = new Queue<double[][]>();
|
||||
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
||||
ButtonStartGame = new RelayCommand(BeginGame);
|
||||
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
|
||||
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
|
||||
data.Client.CReset = CanvasResetData;
|
||||
}
|
||||
|
||||
public ICommand OnKeyDown { get; set; }
|
||||
public ICommand ButtonStartGame { get; set; }
|
||||
public ICommand ButtonResetCanvas { get; set; }
|
||||
|
||||
public void BeginGame()
|
||||
{
|
||||
|
||||
queueTimer = new Timer(50);
|
||||
queueTimer.Start();
|
||||
queueTimer.Elapsed += sendArrayFromQueue;
|
||||
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
||||
}
|
||||
|
||||
|
||||
private void CanvasResetLocal()
|
||||
{
|
||||
this.window.CanvasForPaint.Children.Clear();
|
||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
|
||||
}
|
||||
|
||||
|
||||
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
||||
{
|
||||
if (e.ButtonState == MouseButtonState.Pressed)
|
||||
{
|
||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||
}
|
||||
}
|
||||
|
||||
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
||||
{
|
||||
if (e.LeftButton == MouseButtonState.Pressed)
|
||||
{
|
||||
double[] coordinates = new double[4];
|
||||
Line line = new Line();
|
||||
|
||||
line.Stroke = new SolidColorBrush(color);
|
||||
//line.Stroke = SystemColors.WindowFrameBrush;
|
||||
line.X1 = currentPoint.X;
|
||||
line.Y1 = currentPoint.Y;
|
||||
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
||||
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
||||
coordinates[0] = line.X1;
|
||||
coordinates[1] = line.Y1;
|
||||
coordinates[2] = line.X2;
|
||||
coordinates[3] = line.Y2;
|
||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||
buffer[pos] = coordinates;
|
||||
pos++;
|
||||
|
||||
window.CanvasForPaint.Children.Add(line);
|
||||
if (pos == maxLines)
|
||||
{
|
||||
double[][] temp = new double[maxLines][];
|
||||
for (int i = 0; i < maxLines; i++)
|
||||
{
|
||||
temp[i] = buffer[i];
|
||||
}
|
||||
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";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@
|
||||
</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"/>
|
||||
|
||||
<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">
|
||||
|
||||
@@ -9,10 +9,13 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using static SharedClientServer.JSONConvert;
|
||||
|
||||
namespace Server.Models
|
||||
{
|
||||
public delegate void Callback();
|
||||
class ServerClient : ObservableObject
|
||||
{
|
||||
private TcpClient tcpClient;
|
||||
@@ -22,7 +25,8 @@ namespace Server.Models
|
||||
private int totalBufferReceived = 0;
|
||||
public User User { get; set; }
|
||||
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
|
||||
|
||||
private Callback OnMessageReceivedOk;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
||||
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
Debug.WriteLine("[SERVERCLIENT] Client disconnected! exception was " + e.Message);
|
||||
tcpClient.Close();
|
||||
ServerCommunication.INSTANCE.ServerClientDisconnect(this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -108,21 +113,21 @@ namespace Server.Models
|
||||
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
|
||||
byte id = message[4];
|
||||
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));
|
||||
switch(id)
|
||||
switch (id)
|
||||
{
|
||||
|
||||
|
||||
case JSONConvert.LOGIN:
|
||||
// json log in username data
|
||||
string uName = JSONConvert.GetUsernameLogin(payload);
|
||||
|
||||
|
||||
if (uName != null)
|
||||
{
|
||||
User = new User(uName);
|
||||
User.Username = uName;
|
||||
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
|
||||
|
||||
|
||||
}
|
||||
break;
|
||||
case JSONConvert.MESSAGE:
|
||||
@@ -145,51 +150,58 @@ namespace Server.Models
|
||||
case JSONConvert.LOBBY:
|
||||
// lobby data
|
||||
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
||||
handleLobbyMessage(payload,l);
|
||||
handleLobbyMessage(payload, l);
|
||||
break;
|
||||
|
||||
case JSONConvert.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;
|
||||
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
|
||||
// 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;
|
||||
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:
|
||||
//Flag byte for receiving the random word.
|
||||
break;
|
||||
case JSONConvert.MESSAGE_RECEIVED:
|
||||
// we now can send a new message
|
||||
OnMessageReceivedOk?.Invoke();
|
||||
break;
|
||||
|
||||
default:
|
||||
Debug.WriteLine("[SERVER] Received weird identifier: " + id);
|
||||
@@ -218,6 +230,15 @@ namespace Server.Models
|
||||
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
|
||||
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
|
||||
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;
|
||||
case LobbyIdentifier.LEAVE:
|
||||
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>
|
||||
/// sends a message to the tcp client
|
||||
/// </summary>
|
||||
|
||||
@@ -90,7 +90,7 @@ namespace Server.Models
|
||||
/// send a message to all tcp clients in the list
|
||||
/// </summary>
|
||||
/// <param name="message">the message to send</param>
|
||||
public void sendToAll(byte[] message)
|
||||
public async void sendToAll(byte[] message)
|
||||
{
|
||||
foreach (ServerClient sc in serverClients)
|
||||
{
|
||||
@@ -142,6 +142,7 @@ namespace Server.Models
|
||||
{
|
||||
foreach (ServerClient sc in serverClientsInlobbies[l])
|
||||
{
|
||||
Debug.WriteLine("[SERVERCLIENT] Sending message");
|
||||
sc.sendMessage(message);
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -6,6 +6,16 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="resources\WordsForGame.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="resources\WordsForGame.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
|
||||
<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 Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace SharedClientServer
|
||||
{
|
||||
class JSONConvert
|
||||
{
|
||||
public const byte LOGIN = 0x01;
|
||||
public const byte MESSAGE = 0x02;
|
||||
public const byte LOBBY = 0x03;
|
||||
public const byte CANVAS = 0x04;
|
||||
public const byte GAME = 0x05;
|
||||
|
||||
public const int CANVAS_WRITING = 0;
|
||||
public const int CANVAS_RESET = 1;
|
||||
|
||||
|
||||
public enum LobbyIdentifier
|
||||
{
|
||||
HOST,
|
||||
JOIN,
|
||||
JOIN_SUCCESS,
|
||||
LEAVE,
|
||||
LIST,
|
||||
REQUEST
|
||||
}
|
||||
|
||||
public static (string,string) GetUsernameAndMessage(byte[] json)
|
||||
{
|
||||
string msg = Encoding.UTF8.GetString(json);
|
||||
dynamic payload = JsonConvert.DeserializeObject(msg);
|
||||
|
||||
return (payload.username, payload.message);
|
||||
}
|
||||
|
||||
public static string GetUsernameLogin(byte[] json)
|
||||
{
|
||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||
return payload.username;
|
||||
}
|
||||
|
||||
public static byte[] ConstructUsernameMessage(string uName)
|
||||
{
|
||||
return GetMessageToSend(LOGIN, new
|
||||
{
|
||||
username = uName
|
||||
});
|
||||
}
|
||||
|
||||
#region lobby messages
|
||||
|
||||
public static byte[] ConstructLobbyHostMessage()
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.HOST
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.HOST,
|
||||
id = lobbyID
|
||||
}) ;
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyRequestMessage()
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.REQUEST
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.LIST,
|
||||
lobbies = lobbiesList
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.JOIN,
|
||||
id = lobbyID
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.LEAVE,
|
||||
id = lobbyID
|
||||
});
|
||||
}
|
||||
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
||||
{
|
||||
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));
|
||||
JArray lobbiesArray = payload.lobbies;
|
||||
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
||||
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
||||
Debug.WriteLine("lobbies in array: ");
|
||||
foreach (Lobby l in lobbiesTemp)
|
||||
{
|
||||
Debug.WriteLine("players: " + l.PlayersIn);
|
||||
}
|
||||
return lobbiesTemp;
|
||||
}
|
||||
|
||||
public static int GetLobbyID(byte[] json)
|
||||
{
|
||||
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));
|
||||
JObject dynamicAsObject = payload.lobby;
|
||||
return dynamicAsObject.ToObject<Lobby>();
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyJoinSuccessMessage(bool 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));
|
||||
return payload.host;
|
||||
}
|
||||
|
||||
#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>
|
||||
/// constructs a message that can be sent to the clients or server
|
||||
/// </summary>
|
||||
/// <param name="identifier">the identifier for what kind of message it is</param>
|
||||
/// <param name="payload">the json payload</param>
|
||||
/// <returns>a byte array containing a message that can be sent to clients or server</returns>
|
||||
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
|
||||
{
|
||||
// convert the dynamic to bytes
|
||||
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
|
||||
byte[] res = new byte[payloadBytes.Length + 5];
|
||||
// put the payload in the res array
|
||||
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
|
||||
// put the identifier at the start of the payload part
|
||||
res[4] = identifier;
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
using Client;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace SharedClientServer
|
||||
{
|
||||
class JSONConvert
|
||||
{
|
||||
public const byte LOGIN = 0x01;
|
||||
public const byte MESSAGE = 0x02;
|
||||
public const byte LOBBY = 0x03;
|
||||
public const byte CANVAS = 0x04;
|
||||
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
|
||||
{
|
||||
HOST,
|
||||
JOIN,
|
||||
JOIN_SUCCESS,
|
||||
LEAVE,
|
||||
LIST,
|
||||
REQUEST
|
||||
}
|
||||
|
||||
public static (string,string) GetUsernameAndMessage(byte[] json)
|
||||
{
|
||||
string msg = Encoding.UTF8.GetString(json);
|
||||
dynamic payload = JsonConvert.DeserializeObject(msg);
|
||||
|
||||
return (payload.username, payload.message);
|
||||
}
|
||||
|
||||
public static string GetUsernameLogin(byte[] json)
|
||||
{
|
||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||
return payload.username;
|
||||
}
|
||||
|
||||
public static byte[] ConstructUsernameMessage(string uName)
|
||||
{
|
||||
return GetMessageToSend(LOGIN, new
|
||||
{
|
||||
username = uName
|
||||
});
|
||||
}
|
||||
|
||||
#region lobby messages
|
||||
|
||||
public static byte[] ConstructLobbyHostMessage()
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.HOST
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.HOST,
|
||||
id = lobbyID
|
||||
}) ;
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyRequestMessage()
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.REQUEST
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.LIST,
|
||||
lobbies = lobbiesList
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.JOIN,
|
||||
id = lobbyID
|
||||
});
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
|
||||
{
|
||||
return GetMessageToSend(LOBBY, new
|
||||
{
|
||||
identifier = LobbyIdentifier.LEAVE,
|
||||
id = lobbyID
|
||||
});
|
||||
}
|
||||
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
||||
{
|
||||
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));
|
||||
JArray lobbiesArray = payload.lobbies;
|
||||
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
||||
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
||||
Debug.WriteLine("lobbies in array: ");
|
||||
foreach (Lobby l in lobbiesTemp)
|
||||
{
|
||||
Debug.WriteLine("players: " + l.PlayersIn);
|
||||
}
|
||||
return lobbiesTemp;
|
||||
}
|
||||
|
||||
public static int GetLobbyID(byte[] json)
|
||||
{
|
||||
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));
|
||||
JObject dynamicAsObject = payload.lobby;
|
||||
return dynamicAsObject.ToObject<Lobby>();
|
||||
}
|
||||
|
||||
public static byte[] ConstructLobbyJoinSuccessMessage(bool 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));
|
||||
return payload.host;
|
||||
}
|
||||
|
||||
#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>
|
||||
/// constructs a message that can be sent to the clients or server
|
||||
/// </summary>
|
||||
/// <param name="identifier">the identifier for what kind of message it is</param>
|
||||
/// <param name="payload">the json payload</param>
|
||||
/// <returns>a byte array containing a message that can be sent to clients or server</returns>
|
||||
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
|
||||
{
|
||||
// convert the dynamic to bytes
|
||||
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
|
||||
byte[] res = new byte[payloadBytes.Length + 5];
|
||||
// put the payload in the res array
|
||||
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
|
||||
// put the identifier at the start of the payload part
|
||||
res[4] = identifier;
|
||||
// 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