76 Commits

Author SHA1 Message Date
Dogukan
ec08fbfced [ADDITION] added a new property to the user (may be removed later on), and made a check for the random word 2020-10-23 15:47:52 +02:00
SemvdH
b14a7691b5 Merge pull request #12 from SemvdH/hotfix/fixClientServerComms
[FIX] Callbacks weren't properly called
2020-10-23 14:56:45 +02:00
Dogukan
7df48ab322 [FIX] Callbacks weren't properly called 2020-10-23 14:49:20 +02:00
Sem van der Hoeven
80d970da35 [FIX] made login impossible if no name was entered 2020-10-23 14:13:22 +02:00
SemvdH
2c7bf3e217 Merge pull request #11 from SemvdH/setupBranch
merge Setup branch into master
2020-10-23 14:06:36 +02:00
SemvdH
92f57a87bc Merge pull request #10 from SemvdH/update-scores
added updating scores on lobby list receive
2020-10-23 13:59:28 +02:00
Sem van der Hoeven
da5528c7b2 added updating scores on lobby list receive 2020-10-23 13:58:44 +02:00
Lars
c16f7cf68f Merge branch 'master' into setupBranch 2020-10-23 13:11:56 +02:00
SemvdH
5c2dea3ab4 Merge pull request #9 from SemvdH/feature/playerList
Feature/player list
2020-10-23 12:53:43 +02:00
SemvdH
e2f9dfec78 Merge branch 'master' into feature/playerList 2020-10-23 12:53:35 +02:00
Dogukan
7fcf424b65 [FIX] fixed the async for updating the label, as well as the chat messages 2020-10-23 12:48:27 +02:00
Dogukan
97be0f937c [Cleanup] cleaned a null checking if-statement for the lobby id 2020-10-23 12:42:24 +02:00
Dogukan
09056818df Merge remote-tracking branch 'origin/feature/playerList' into feature/playerList 2020-10-23 12:33:06 +02:00
Dogukan
8d4f72c09d [CHANGED] Static function for handling to callbacks 2020-10-23 12:32:11 +02:00
Sem van der Hoeven
f51d310787 [EDIT] removed uneccesary call to updatelobbies 2020-10-23 12:31:01 +02:00
Sem van der Hoeven
9e829c47ff [FIX] lobbies now get correctly updated when someone leaves or joins 2020-10-23 12:26:31 +02:00
Lars
f5d55ef405 [FIX] randomword is not visible 2020-10-23 11:54:43 +02:00
Dogukan
0d44b2d840 [TRY] tried to bind the label data, doesn't work yet 2020-10-23 11:30:06 +02:00
Dogukan
1c04ab95c0 [ADDED] player list in lobby updates on join! Not on disconnect yet. Tried to set the word label doesn't work yet. 2020-10-22 23:54:07 +02:00
Sem van der Hoeven
ddf4594c5e [ADD] add canvas data sending on mouse up 2020-10-22 22:47:11 +02:00
Sem van der Hoeven
09f9e227b8 merge stuff 2020-10-22 22:35:29 +02:00
SemvdH
ec156f3dc6 Merge pull request #8 from SemvdH/stateful-canvas
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
2020-10-22 22:31:09 +02:00
SemvdH
0158841159 Merge branch 'master' into stateful-canvas 2020-10-22 22:30:42 +02:00
Sem van der Hoeven
8a490eb399 [FIX] AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2020-10-22 22:22:24 +02:00
Sem van der Hoeven
5e408091cb the fuck????? 2020-10-22 22:04:20 +02:00
Lars
24eb43239b [FIX] nog when you click host, you are able to click the start game button 2020-10-22 22:02:41 +02:00
Lars
335d17838c Merge branch 'master' into setupBranch 2020-10-22 20:04:30 +02:00
Lars
242c435ac7 added something little, not that very important tho 2020-10-22 17:46:45 +02:00
Lars
eae05d17df [ADDED] Color can now we transfered, still need to get fixed with the buffer -_- 2020-10-22 17:30:40 +02:00
Sem van der Hoeven
d37696d4bd [FIX] made message sending statful 2020-10-22 17:11:55 +02:00
Sem van der Hoeven
4a400628df [FIX] merge stuff 2020-10-22 17:05:02 +02:00
SemvdH
9fa231ab00 Merge pull request #7 from SemvdH/fix-async-stuff
merge Fix async stuff into master
2020-10-22 17:02:30 +02:00
SemvdH
21ee724056 Merge pull request #6 from SemvdH/feature/jsonForWords
Feature/json for words
2020-10-22 17:01:41 +02:00
SemvdH
5075f285d1 Merge branch 'master' into feature/jsonForWords 2020-10-22 17:01:28 +02:00
Sem van der Hoeven
eca17cc70f [FIX] handled disconnects for everything 2020-10-22 17:00:26 +02:00
Sem van der Hoeven
07b0357b0a Merge branch 'feature/jsonForWords' into fix-async-stuff 2020-10-22 16:37:05 +02:00
Sem van der Hoeven
d8bbaf5258 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:36:45 +02:00
Dogukan
8190d9b31b [ADDITION] added a wait one to the client onread 2020-10-22 16:36:00 +02:00
Sem van der Hoeven
bb289865b7 [ADD] added message received ok 2020-10-22 16:34:31 +02:00
Dogukan
b8d0f206ba [FIX] IT FUCKING WORKS 2020-10-22 16:34:02 +02:00
Sem van der Hoeven
f1878eaf25 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:16:08 +02:00
Dogukan
3b667b3f0c [ADDITION] tried to fix the async methods. 2020-10-22 16:11:19 +02:00
Lars
1fdba622cc Merge branch 'master' into setupBranch 2020-10-22 15:46:20 +02:00
Lars
cac0fdc0a4 [ADDED] lobby now secured when the game starts. start button is still for everyone available, not working yet 2020-10-22 15:40:09 +02:00
Sem van der Hoeven
674c4f1ba1 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 13:55:49 +02:00
Sem van der Hoeven
d3bd1418d1 line 2020-10-22 13:55:46 +02:00
Dogukan
5b5d66c41b [ADDITION] Tried to send the random word to a lobby 2020-10-22 13:55:19 +02:00
SemvdH
d4d0545f0b Merge pull request #5 from SemvdH/feature/hostWhenEnterEmptyLobby
merge Feature/host when enter empty lobby into master
2020-10-22 13:23:30 +02:00
Sem van der Hoeven
0b72c4dc9b [ADD] added that when you join an empty lobby you become the host 2020-10-22 13:22:52 +02:00
Sem van der Hoeven
471247827b [ADD] added host user check to join 2020-10-22 13:13:57 +02:00
Dogukan
ef255e4828 [ADDED] a start for reading the random word from a file 2020-10-22 01:37:59 +02:00
Lars
8190724f77 [ADDED] canvas data sending to the server works, but not fully yet to all the clients 2020-10-21 23:18:37 +02:00
SemvdH
b08e6cc749 Merge pull request #4 from SemvdH/feature/disconnect
merge Feature/disconnect into master
2020-10-21 22:55:28 +02:00
Sem van der Hoeven
c150bf3611 [FIX] fixed handling client disconnect 2020-10-21 22:54:37 +02:00
SemvdH
332fcf799c Merge pull request #3 from SemvdH/feature/handleChatData
merga Feature/handle chat data in master
2020-10-21 22:45:21 +02:00
Dogukan
4d3dda023c Merge branch 'master' into feature/handleChatData 2020-10-21 22:43:18 +02:00
Sem van der Hoeven
e8a72e164f add try catch 2020-10-21 22:41:39 +02:00
Dogukan
d5d6d59690 [FIX] fixed the broadcast for the chat messages. 2020-10-21 22:40:36 +02:00
SemvdH
754c1c5db9 Merge pull request #2 from SemvdH/feature/leaveLobby
merge Feature/leave lobby into master
2020-10-21 22:34:27 +02:00
Sem van der Hoeven
8a90e74e74 [FIX] fixed leaving lobby 2020-10-21 22:32:56 +02:00
Sem van der Hoeven
be99c8d3f9 [FIX] fixed equals operators 2020-10-21 22:18:37 +02:00
Sem van der Hoeven
9e1ac07b80 [ADD] added equals operators 2020-10-21 22:03:20 +02:00
Sem van der Hoeven
cc5c71a30f [ADD] added buttons reenabled when leaving 2020-10-21 21:55:28 +02:00
Sem van der Hoeven
442cdccc49 [ADD] add updating lobbies on exiting window 2020-10-21 21:40:35 +02:00
Sem van der Hoeven
c339746a82 [ADD] add closing method 2020-10-21 21:05:04 +02:00
SemvdH
0f01354b72 Merge pull request #1 from SemvdH/setupBranch
merge Setup branch into develop
2020-10-21 20:59:02 +02:00
Sem van der Hoeven
61577e0df7 [FIX] fixed merge conflicts 2020-10-21 20:56:38 +02:00
Sem van der Hoeven
298bd760e5 Merge remote-tracking branch 'origin/feature/sendingCanvasData' into setupBranch 2020-10-21 20:45:51 +02:00
Sem van der Hoeven
c4c97a3fbe Merge branch 'lobbies' into setupBranch 2020-10-21 20:44:11 +02:00
Dogukan
a4e45b1a6b [MISC] tried to send the message to the current lobby, didn't work. 2020-10-21 20:43:28 +02:00
Lars
4f07eeb95a useless 2020-10-21 20:24:26 +02:00
Dogukan
74f8e868f6 [ADDITION] servercommunication towards the client.
Still in progress not functional because of a null exception when receiving the broadcast message.
2020-10-21 17:47:48 +02:00
Dogukan
381c142eaa [ADDITION] Added databinding to the chatbox function.
Tried to broadcast the message, doesn't work yet.
2020-10-20 23:54:29 +02:00
Lars
2aeca40aa4 its not working yet, its getting a System.OutOfMemoryException, needs to be fixed 2020-10-20 23:52:10 +02:00
Dogukan
4d161391b1 Merge remote-tracking branch 'origin/setupBranch' into setupBranch 2020-10-20 19:53:35 +02:00
Dogukan
7dbdcc8bcc [ADDITION] fixed the chatbox size 2020-10-20 19:53:28 +02:00
19 changed files with 1018 additions and 226 deletions

View File

@@ -2,28 +2,54 @@
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;
using static SharedClientServer.JSONConvert;
namespace Client
{
public delegate void OnLobbyCreated(int id);
public delegate void LobbyJoinCallback(bool isHost);
public delegate void RandomWord(string word);
public delegate void HandleIncomingMsg(string username, string msg);
internal delegate void HandleIncomingPlayer(Lobby lobby);
public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset();
public delegate void LobbyCallback(int id);
class Client : ObservableObject
{
private ClientData clientData = ClientData.Instance;
private TcpClient tcpClient;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024];
private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0;
public int Port = 5555;
public bool Connected = false;
private string username;
public Callback OnSuccessfullConnect;
public Callback OnLobbiesListReceived;
public Callback OnLobbyJoinSuccess;
public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost;
public OnLobbyCreated OnLobbyCreated;
public Callback OnServerDisconnect;
public Callback OnLobbyUpdate;
public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave;
public RandomWord RandomWord;
public HandleIncomingMsg IncomingMsg;
public HandleIncomingPlayer IncomingPlayer;
private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset;
public HandleIncomingPlayer UpdateUserScores;
public Lobby[] Lobbies { get; set; }
public Client(string username)
@@ -37,49 +63,73 @@ 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();
OnLobbyUpdate = updateGameLobby;
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 > 1024)
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);
if (totalBufferReceived + amountReceived > 2048)
{
throw new OutOfMemoryException("buffer too small");
}
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);
}
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived;
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
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;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke();
}
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
}
private void handleData(byte[] message)
{
byte id = message[4];
byte[] payload = new byte[message.Length - 5];
Array.Copy(message, 5, payload, 0, message.Length - 5);
Debug.WriteLine("[CLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
switch (id)
{
case JSONConvert.LOGIN:
@@ -90,8 +140,20 @@ namespace Client
(string, string) combo = JSONConvert.GetUsernameAndMessage(payload);
string textUsername = combo.Item1;
string textMsg = combo.Item2;
//TODO display username and message in chat window
if (textUsername != data.User.Username)
{
IncomingMsg?.Invoke(textUsername, textMsg);
}
if (textMsg == data.User.RandomWord && !string.IsNullOrEmpty(data.User.RandomWord))
{
Debug.WriteLine($"[CLIENT] word has been guessed! {data.User.Username} + Word: {data.User.RandomWord}");
}
//TODO display username and message in chat window
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
break;
case JSONConvert.LOBBY:
@@ -104,6 +166,7 @@ namespace Client
Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
OnLobbiesListReceived?.Invoke();
OnLobbiesReceivedAndWaitingForHost?.Invoke();
OnLobbyUpdate?.Invoke();
break;
case LobbyIdentifier.HOST:
// we receive this when the server has made us a host of a new lobby
@@ -113,21 +176,68 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID);
break;
case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke();
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break;
case LobbyIdentifier.LEAVE:
int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
OnLobbyLeave?.Invoke(lobbyLeaveID);
break;
}
//TODO fill lobby with the data received
break;
case JSONConvert.CANVAS:
// 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));
break;
}
break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload);
data.User.RandomWord = JSONConvert.GetRandomWord(payload);
data.User.TurnToDraw = true; // Dit is test code, dit kan weg zodra alles lopende is.
if (data.Lobby?.ID == lobbyId && data.User.TurnToDraw)
RandomWord?.Invoke(data.User.RandomWord);
break;
default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break;
}
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED, null));
}
/*
* Updates the current lobby with the joining players,
* their player score is also tracked and should always be zero.
*/
private void updateGameLobby()
{
Debug.WriteLine("[CLIENT] updating game lobby");
foreach (var item in Lobbies)
{
Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count);
if (item.ID == data.Lobby?.ID)
{
//IncomingPlayer?.Invoke(item);
UpdateUserScores?.Invoke(item as Lobby);
}
}
}
public void SendMessage(byte[] message)
{
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message));
@@ -138,6 +248,7 @@ namespace Client
{
Debug.WriteLine("[CLIENT] finished writing");
stream.EndWrite(ar);
stream.Flush();
}
}
}

View File

@@ -30,6 +30,8 @@ namespace Client
private User _user;
private Client _client;
private Lobby _lobby;
private string _message;
private double[] _canvasData = new double[4];
private ClientData()
{
@@ -55,5 +57,23 @@ namespace Client
set { _lobby = value; }
}
public String Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
public double[] CanvasData
{
get { return _canvasData; }
set { _canvasData = value; }
}
}
}

View File

@@ -11,6 +11,9 @@ 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;
namespace Client
{
@@ -34,6 +37,11 @@ namespace Client
_lobbies = new ObservableCollection<Lobby>();
client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies;
client.OnLobbyLeave = leaveLobby;
client.OnServerDisconnect = () =>
{
Environment.Exit(0);
};
OnHostButtonClick = new RelayCommand(hostGame);
@@ -41,21 +49,28 @@ namespace Client
JoinSelectedLobby = new RelayCommand(joinLobby, true);
}
private void leaveLobby(int id)
{
_model.CanStartGame = true;
ClientData.Instance.Lobby = null;
SelectedLobby = null;
}
private void hostGame()
{
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
client.OnLobbyCreated = becomeHostForLobby;
}
private void becomeHostForLobby(int id)
{
Debug.WriteLine($"got host succes with data {id} ");
wantToBeHost = true;
wantToBeHostId = id;
ClientData.Instance.User.Host = true;
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
}
private void hostLobbiesReceived()
@@ -77,14 +92,21 @@ namespace Client
private void joinLobby()
{
// lobby die je wilt joinen verwijderen
// nieuwe binnengekregen lobby toevoegen
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));
}
}
private void OnLobbyJoinSuccess()
private void OnLobbyJoinSuccess(bool isHost)
{
ClientData.Instance.User.Host = isHost;
startGameInLobby();
}
@@ -92,29 +114,21 @@ namespace Client
private void updateLobbies()
{
Debug.WriteLine("updating lobbies...");
Debug.WriteLine("[VIEWMODEL] updating lobbies...");
Lobby[] lobbiesArr = client.Lobbies;
Application.Current.Dispatcher.Invoke(delegate
{
//for (int i = 0; i < lobbiesArr.Length; i++)
//{
// Lobby lobby = lobbiesArr[i];
// Debug.WriteLine(lobby.PlayersIn);
// if (i < _lobbies.Count && _lobbies[i].ID == lobby.ID)
// {
// _lobbies[i].Set(lobby);
// } else
// {
// _lobbies.Add(lobbiesArr[i]);
// }
//}
_lobbies.Clear();
foreach (Lobby l in lobbiesArr)
{
_lobbies.Add(l);
Lobby clientLobby = ClientData.Instance.Lobby;
if (l.ID == clientLobby?.ID)
{
clientLobby = l;
}
}
});
@@ -168,5 +182,7 @@ namespace Client
get { return _lobbies; }
set { _lobbies = value; }
}
}
}

View File

@@ -1,10 +1,271 @@
using System.Collections.ObjectModel;
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>();
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
private dynamic _payload;
public string _username;
public string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
}
}
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
public bool IsHost
{
get { return data.User.Host; }
}
public ViewModelGame(GameWindow window)
{
this.window = window;
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;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
data.Client.UpdateUserScores = UpdateUserScores;
}
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;
}
}
}
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
sendArrayFromQueue(sender, null);
}
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
{
if (linesQueue.Count != 0)
{
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 void HandleIncomingMsg(string username, string message)
{
Application.Current.Dispatcher.Invoke(delegate
{
Messages.Add($"{username}: {message}");
});
}
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
}
public void HandleRandomWord(string randomWord)
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Application.Current.Dispatcher.Invoke(delegate
{
RandomWord = randomWord;
});
}
public void HandleIncomingPlayer(Lobby lobby)
{
Application.Current.Dispatcher.Invoke(delegate
{
Players.Clear();
foreach (var item in lobby.Users)
{
Players.Add(item.Username + "\n" + item.Score);
}
});
}
private void UpdateUserScores(Lobby newLobby) {
Debug.WriteLine("[GAME] updating user scores");
List<User> newUsers = newLobby.Users;
// go over all users in current lobby
foreach (User user in data.Lobby?.Users)
{
// check with all users in new lobby
foreach (User newUser in newUsers)
{
// and update the score
if (newUser.Username == user.Username)
{
Debug.WriteLine($"[GAME] setting score of {user.Username} to {newUser.Score}. it was {user.Score}");
user.Score = newUser.Score;
break;
}
}
}
// update all the scores in the player list
HandleIncomingPlayer(newLobby);
}
}
}

View File

@@ -3,7 +3,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Client.Views"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
Title="Scrubl.io" Height="600" Width="1200">
@@ -23,24 +22,32 @@
<Grid Grid.Column="0" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ListBox Name="PlayerList" ItemsSource="{Binding Path=Players}" Margin="10,0,0,10" FontSize="20"/>
</Grid>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/>
<Grid Grid.Row="0" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="2" Content="{Binding Path=RandomWord, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20"/>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
</Grid>
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
<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">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove" MouseUp="CanvasForPaint_MouseUp">
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>
@@ -48,8 +55,13 @@
</Border>
<Grid Grid.Column="2" Grid.Row="1">
<TextBox Name="SentMessage" IsReadOnly="True"/>
<TextBox x:Name="ChatBox" Keyboard.KeyDown="ChatBox_KeyDown" Width="200" Height="50" ToolTip="Message goes here" ToolTipService.IsEnabled="True" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,10,69" />
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,10,0">
<TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings>
</TextBox>
</Grid>
</Grid>

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
using SharedClientServer;
using Client.ViewModels;
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Text;
@@ -26,8 +27,12 @@ namespace Client.Views
private void Button_EnterUsername(object sender, RoutedEventArgs e)
{
User user = new User(usernameTextbox.Text);
string name = usernameTextbox.Text;
if (name == string.Empty) return;
User user = new User(name);
Client client = new Client(user.Username);
LoginButton.IsEnabled = false;
client.OnSuccessfullConnect = () =>
{
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
@@ -41,6 +46,7 @@ namespace Client.Views
});
};
}
}
}

View File

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

View File

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

View File

@@ -1,23 +1,32 @@

using Client;
using Newtonsoft.Json.Linq;
using SharedClientServer;
using System;
using System.Collections.Generic;
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;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
private byte[] totalBuffer = new byte[1024];
private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048];
private string _randomWord = "";
private int totalBufferReceived = 0;
public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
private Callback OnMessageReceivedOk;
/// <summary>
@@ -42,47 +51,59 @@ namespace Server.Models
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024)
try
{
throw new OutOfMemoryException("buffer is too small!");
}
int bytesReceived = this.stream.EndRead(ar);
// copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount
totalBufferReceived += bytesReceived;
// calculate the expected length of the message
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{
// we have received the full packet
byte[] message = new byte[expectedMessageLength];
// copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
HandleIncomingMessage(message);
// move the contents of the totalbuffer to the start of the array
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength));
// remove the length of the expected message from the total buffer
totalBufferReceived -= expectedMessageLength;
// and set the new expected length to the rest that is still in the buffer
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
if (expectedMessageLength == 0)
if (totalBufferReceived + bytesReceived > 2048)
{
break;
throw new OutOfMemoryException("buffer is too small!");
}
// copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount
totalBufferReceived += bytesReceived;
// calculate the expected length of the message
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{
// we have received the full packet
byte[] message = new byte[expectedMessageLength];
// copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
HandleIncomingMessage(message);
// move the contents of the totalbuffer to the start of the array
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength));
// remove the length of the expected message from the total buffer
totalBufferReceived -= expectedMessageLength;
// and set the new expected length to the rest that is still in the buffer
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
if (expectedMessageLength == 0)
{
break;
}
}
ar.AsyncWaitHandle.WaitOne();
// start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
}
// 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);
}
}
@@ -95,9 +116,9 @@ 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:
@@ -118,18 +139,78 @@ namespace Server.Models
string textUsername = combo.Item1;
string textMsg = combo.Item2;
// todo handle sending to all except this user the username and message to display in chat
//Takes the data sent from the client, and then sets it in a data packet to be sent.
dynamic packet = new
{
username = textUsername,
message = textMsg
};
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
{
Debug.WriteLine($"[SERVERCLIENT] word has been guessed! {User.Username} + Word: {_randomWord}");
}
//Sends the incomming message to be broadcast to all of the clients inside the current lobby.
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
break;
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;
}
// canvas data
// todo send canvas data to all other serverclients in lobby
break;
case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload);
switch (command)
{
case "startGame":
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID);
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
}
break;
case JSONConvert.RANDOMWORD:
//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);
break;
@@ -153,13 +234,45 @@ namespace Server.Models
break;
case LobbyIdentifier.JOIN:
int id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.JoinLobby(this.User,id);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
bool isHost;
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () =>
{
_randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{
id = serverCom.GetLobbyForUser(User).ID,
word = _randomWord
}));
OnMessageReceivedOk = null;
};
break;
case LobbyIdentifier.LEAVE:
id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.LeaveLobby(User, id);
sendMessage(JSONConvert.ConstructLobbyLeaveMessage(id));
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
}
}
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>

View File

@@ -1,5 +1,4 @@

using Client;
using Client;
using SharedClientServer;
using System;
using System.Collections.Generic;
@@ -17,6 +16,7 @@ namespace Server.Models
public bool Started = false;
public List<Lobby> lobbies;
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
internal Action DisconnectClientAction;
public Action newClientAction;
@@ -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)
{
@@ -98,6 +98,26 @@ namespace Server.Models
}
}
public void ServerClientDisconnect(ServerClient serverClient)
{
Debug.WriteLine("[SERVERCOMM] handling disconnect");
DisconnectClientAction?.Invoke();
int id = -1;
foreach (Lobby l in serverClientsInlobbies.Keys)
{
if (serverClientsInlobbies[l].Contains(serverClient))
{
id = l.ID;
}break;
}
if (id != -1)
{
LeaveLobby(serverClient.User, id);
SendToAllExcept(serverClient, JSONConvert.ConstructLobbyLeaveMessage(id));
}
}
public void SendToAllExcept(string username, byte[] message)
{
foreach (ServerClient sc in serverClients)
@@ -106,7 +126,31 @@ namespace Server.Models
}
}
public void SendToAllExcept(ServerClient sc, byte[] message)
{
foreach (ServerClient s in serverClients)
{
if (s != sc) s.sendMessage(message);
}
}
public void SendToLobby(Lobby lobby, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l == lobby)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
Debug.WriteLine("[SERVERCLIENT] Sending message");
sc.sendMessage(message);
}
break;
}
}
}
public void SendCanvasDataToLobby(Lobby lobby, string username, byte[] message)
{
foreach (Lobby l in lobbies)
{
@@ -162,6 +206,7 @@ namespace Server.Models
}
}
public int HostForLobby(User user)
{
Lobby lobby = new Lobby( lobbies.Count + 1,0, 8);
@@ -172,17 +217,69 @@ namespace Server.Models
return lobby.ID;
}
public void JoinLobby(User user, int id)
public void JoinLobby(User user, int id, out bool isHost)
{
isHost = false;
foreach (Lobby l in lobbies)
{
if (l.ID == id)
{
if (l.Users.Count == 0)
{
user.Host = true;
isHost = true;
}
AddToLobby(l, user);
Debug.WriteLine($"{user.Username} joined lobby with id {id}");
break;
}
}
}
public void LeaveLobby(User user, int id)
{
Debug.WriteLine("[SERVERCOMM] removing user from lobby");
foreach (Lobby l in lobbies)
{
if (l.ID == id)
{
Debug.WriteLine($"[SERVERCOMM] checking for lobby with id {l.ID}");
foreach (User u in l.Users)
{
Debug.WriteLine($"[SERVERCOMM] checking if {u.Username} is {user.Username} ");
// contains doesn't work, so we'll do it like this...
if (u.Username == user.Username)
{
Debug.WriteLine("[SERVERCOMM] removed user from lobby!");
l.Users.Remove(user);
foreach (ServerClient sc in serverClients)
{
if (sc.User.Username == user.Username)
{
serverClientsInlobbies[l].Remove(sc);
break;
}
}
break;
}
}
}
}
}
public void CloseALobby(int lobbyID)
{
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobby.LobbyJoinable = false;
}
}
}
}
}

View File

@@ -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" />

View File

@@ -33,6 +33,10 @@ namespace Server.ViewModels
{
InformationModel.ClientsConnected++;
};
serverCommunication.DisconnectClientAction = () =>
{
InformationModel.ClientsConnected--;
};
//BitmapImage onlineImg = new BitmapImage(new Uri(@"/img/online.png",UriKind.Relative));
//BitmapImage offlineImg = new BitmapImage(new Uri(@"/img/offline.png", UriKind.Relative));

View 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"
]
}

View File

@@ -7,6 +7,8 @@ using System.Text;
namespace SharedClientServer
{
public delegate void Callback();
class ClientServerUtil
{
// creates a message array to send to the server or to clients
@@ -18,6 +20,5 @@ namespace SharedClientServer
Array.Copy(stringAsBytes, 0, res, 1, stringAsBytes.Length);
return res;
}
}
}

View File

@@ -1,11 +1,13 @@
using Client;
using Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media;
namespace SharedClientServer
{
@@ -15,6 +17,13 @@ namespace SharedClientServer
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
{
@@ -25,9 +34,10 @@ namespace SharedClientServer
LIST,
REQUEST
}
public static (string,string) GetUsernameAndMessage(byte[] json)
{
string msg = Encoding.ASCII.GetString(json);
string msg = Encoding.UTF8.GetString(json);
dynamic payload = JsonConvert.DeserializeObject(msg);
return (payload.username, payload.message);
@@ -35,7 +45,7 @@ namespace SharedClientServer
public static string GetUsernameLogin(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.username;
}
@@ -83,6 +93,7 @@ namespace SharedClientServer
});
}
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
{
return GetMessageToSend(LOBBY, new
@@ -102,13 +113,13 @@ namespace SharedClientServer
}
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.identifier;
}
public static Lobby[] GetLobbiesFromMessage(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JArray lobbiesArray = payload.lobbies;
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
@@ -122,24 +133,98 @@ namespace SharedClientServer
public static int GetLobbyID(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.id;
}
public static Lobby GetLobby(byte[] json)
{
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JObject dynamicAsObject = payload.lobby;
return dynamicAsObject.ToObject<Lobby>();
}
public static byte[] ConstructLobbyJoinSuccessMessage()
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
{
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS});
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>
@@ -149,7 +234,8 @@ namespace SharedClientServer
public static byte[] GetMessageToSend(byte identifier, dynamic payload)
{
// convert the dynamic to bytes
byte[] payloadBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload));
string json = JsonConvert.SerializeObject(payload);
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
// make the array that holds the message and copy the payload into it with the first spot containing the identifier
byte[] res = new byte[payloadBytes.Length + 5];
// put the payload in the res array
@@ -161,6 +247,40 @@ namespace SharedClientServer
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;
}
}
}

View File

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

View File

@@ -1,22 +1,27 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace SharedClientServer
{
class User
class User : IEquatable<User>
{
private string _username;
private int _score;
private bool _host;
private bool _turnToDraw;
private string _message;
private string _randomWord;
[JsonConstructor]
public User(string username, int score, bool host)
public User(string username, int score, bool host, bool turnToDraw)
{
_username = username;
_score = score;
_host = host;
_turnToDraw = turnToDraw;
}
public User(string username)
@@ -24,6 +29,43 @@ namespace SharedClientServer
_username = username;
_score = 0;
_host = false;
_turnToDraw = false;
}
public static bool operator ==(User u1, User u2)
{
if (object.ReferenceEquals(u1, null))
{
return object.ReferenceEquals(u2, null);
}
return u1.Equals(u2 as object);
}
public static bool operator !=(User u1, User u2)
{
if (object.ReferenceEquals(u1, null))
{
return object.ReferenceEquals(u2, null);
}
return u1.Equals(u2 as object);
}
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
return this.Equals(obj as User);
}
}
public bool Equals([AllowNull] User other)
{
return other.Username == this.Username;
}
public string Username
@@ -43,5 +85,16 @@ namespace SharedClientServer
get { return _host; }
set { _host = value; }
}
public bool TurnToDraw
{
get { return _turnToDraw; }
set { _turnToDraw = value; }
}
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
}
}