16 Commits

Author SHA1 Message Date
SemvdH
5075f285d1 Merge branch 'master' into feature/jsonForWords 2020-10-22 17:01:28 +02:00
Dogukan
8190d9b31b [ADDITION] added a wait one to the client onread 2020-10-22 16:36:00 +02:00
Dogukan
b8d0f206ba [FIX] IT FUCKING WORKS 2020-10-22 16:34:02 +02:00
Dogukan
3b667b3f0c [ADDITION] tried to fix the async methods. 2020-10-22 16:11:19 +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
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
10 changed files with 282 additions and 76 deletions

View File

@@ -9,6 +9,7 @@ using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyCallback(int id); public delegate void LobbyCallback(int id);
public delegate void LobbyJoinCallback(bool isHost);
class Client : ObservableObject class Client : ObservableObject
{ {
private TcpClient tcpClient; private TcpClient tcpClient;
@@ -21,10 +22,11 @@ namespace Client
private string username; private string username;
public Callback OnSuccessfullConnect; public Callback OnSuccessfullConnect;
public Callback OnLobbiesListReceived; public Callback OnLobbiesListReceived;
public Callback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave; public LobbyCallback OnLobbyLeave;
private ClientData data = ClientData.Instance;
public Lobby[] Lobbies { get; set; } public Lobby[] Lobbies { get; set; }
public Client(string username) public Client(string username)
@@ -47,6 +49,9 @@ namespace Client
private void OnReadComplete(IAsyncResult ar) private void OnReadComplete(IAsyncResult ar)
{ {
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
int amountReceived = stream.EndRead(ar); int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 1024) if (totalBufferReceived + amountReceived > 1024)
@@ -72,6 +77,7 @@ namespace Client
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0); expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
} }
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
@@ -82,6 +88,7 @@ namespace Client
byte[] payload = new byte[message.Length - 5]; byte[] payload = new byte[message.Length - 5];
Array.Copy(message, 5, payload, 0, message.Length - 5); Array.Copy(message, 5, payload, 0, message.Length - 5);
Debug.WriteLine("[CLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
switch (id) switch (id)
{ {
case JSONConvert.LOGIN: case JSONConvert.LOGIN:
@@ -93,6 +100,11 @@ namespace Client
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
if(textUsername != data.User.Username)
{
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg);
}
//TODO display username and message in chat window //TODO display username and message in chat window
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!"); Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg); Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
@@ -117,7 +129,8 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID); OnLobbyCreated?.Invoke(lobbyCreatedID);
break; break;
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke();
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
int lobbyLeaveID = JSONConvert.GetLobbyID(payload); int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
@@ -131,6 +144,13 @@ namespace Client
// canvas data // canvas data
break; break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload);
if(data.Lobby?.ID == lobbyId)
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload));
break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;

View File

@@ -85,14 +85,14 @@ namespace Client
private void joinLobby() private void joinLobby()
{ {
// lobby die je wilt joinen verwijderen
// nieuwe binnengekregen lobby toevoegen
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess; client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID)); client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
} }
private void OnLobbyJoinSuccess() private void OnLobbyJoinSuccess(bool isHost)
{ {
ClientData.Instance.User.Host = isHost;
startGameInLobby(); startGameInLobby();
} }

View File

@@ -1,11 +1,12 @@
using Client.Views; using Client.Views;
using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Command;
using SharedClientServer; using SharedClientServer;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes; using System.Windows.Shapes;
@@ -21,13 +22,19 @@ namespace Client.ViewModels
private Point currentPoint = new Point(); private Point currentPoint = new Point();
private Color color; private Color color;
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
private dynamic _payload; private dynamic _payload;
private string _username; public static string Word
{
get;
set;
}
private string _message; public string _username;
public string _message;
public string Message public string Message
{ {
get get
@@ -82,21 +89,10 @@ namespace Client.ViewModels
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B; colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected; color = colorSelected;
} }
public ViewModelGame() public ViewModelGame()
{ {
if (_payload == null)
{
_message = "";
}
else
{
//_message = data.Message;
//_username = data.User.Username;
//Messages.Add($"{data.User.Username}: {Message}");
}
OnKeyDown = new RelayCommand(ChatBox_KeyDown); OnKeyDown = new RelayCommand(ChatBox_KeyDown);
} }
@@ -121,13 +117,32 @@ namespace Client.ViewModels
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
} }
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e) /*
* 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..."); Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
} }
/*
* MISC make this a callback
* Handles the random word that has been received from the server.
*/
public static void HandleRandomWord(string randomWord)
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Word = "NegerPik";
}
} }
} }

View File

@@ -36,6 +36,8 @@
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/> <Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="140,0,109,0"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/> <xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5"> <Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5">

View File

@@ -6,8 +6,11 @@ using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Server.Models namespace Server.Models
@@ -21,7 +24,7 @@ namespace Server.Models
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public User User { get; set; } public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE; private ServerCommunication serverCom = ServerCommunication.INSTANCE;
/// <summary> /// <summary>
/// Constructor that creates a new serverclient object with the given tcp client. /// Constructor that creates a new serverclient object with the given tcp client.
@@ -45,49 +48,57 @@ namespace Server.Models
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return; return;
try
int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024)
{ {
throw new OutOfMemoryException("buffer is too small!"); int bytesReceived = this.stream.EndRead(ar);
}
// copy the received bytes into the buffer if (totalBufferReceived + bytesReceived > 1024)
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; 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);
}
catch (IOException e)
{
tcpClient.Close();
ServerCommunication.INSTANCE.ServerClientDisconnect(this);
} }
// start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
/// <summary> /// <summary>
@@ -99,21 +110,21 @@ namespace Server.Models
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}"); Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
byte id = message[4]; byte id = message[4];
byte[] payload = new byte[message.Length - 5]; byte[] payload = new byte[message.Length - 5];
Array.Copy(message,5,payload,0,message.Length-5); Array.Copy(message, 5, payload, 0, message.Length - 5);
Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload)); Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
switch(id) switch (id)
{ {
case JSONConvert.LOGIN: case JSONConvert.LOGIN:
// json log in username data // json log in username data
string uName = JSONConvert.GetUsernameLogin(payload); string uName = JSONConvert.GetUsernameLogin(payload);
if (uName != null) if (uName != null)
{ {
User = new User(uName); User = new User(uName);
User.Username = uName; User.Username = uName;
Debug.WriteLine("[SERVERCLIENT] set username to " + uName); Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
} }
break; break;
case JSONConvert.MESSAGE: case JSONConvert.MESSAGE:
@@ -122,23 +133,31 @@ namespace Server.Models
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
Debug.WriteLine("[SERVERCLIENT] User name: {0}\t User message: {1}", textUsername, textMsg); //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
};
// todo handle sending to all except this user the username and message to display in chat //Sends the incomming message to be broadcast to all of the clients inside the current lobby.
serverCom.SendToLobby(ServerCommunication.INSTANCE.GetLobbyForUser(User),payload); serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
Debug.WriteLine("Payload has been sent!");
break; break;
case JSONConvert.LOBBY: case JSONConvert.LOBBY:
// lobby data // lobby data
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload); LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
handleLobbyMessage(payload,l); handleLobbyMessage(payload, l);
break; break;
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!"); Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
// canvas data // canvas data
// todo send canvas data to all other serverclients in lobby // todo send canvas data to all other serverclients in lobby
break; break;
case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word.
break;
default: default:
Debug.WriteLine("[SERVER] Received weird identifier: " + id); Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break; break;
@@ -162,9 +181,21 @@ namespace Server.Models
break; break;
case LobbyIdentifier.JOIN: case LobbyIdentifier.JOIN:
int id = JSONConvert.GetLobbyID(payload); int id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.JoinLobby(this.User,id); ServerCommunication.INSTANCE.JoinLobby(this.User, id);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage()); 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())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
//Task.Run(SendLobbyData);
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{
id = serverCom.GetLobbyForUser(User).ID,
word = JSONConvert.SendRandomWord("WordsForGame.json")
}));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
id = JSONConvert.GetLobbyID(payload); id = JSONConvert.GetLobbyID(payload);
@@ -175,6 +206,21 @@ namespace Server.Models
} }
} }
private async void SendLobbyData()
{
string result = await WaitForData();
if(result == "bruh momento")
{
}
}
private async Task<string> WaitForData()
{
await Task.Delay(1000);
return "bruh momento";
}
/// <summary> /// <summary>
/// sends a message to the tcp client /// sends a message to the tcp client
/// </summary> /// </summary>

View File

@@ -16,6 +16,7 @@ namespace Server.Models
public bool Started = false; public bool Started = false;
public List<Lobby> lobbies; public List<Lobby> lobbies;
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies; private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
internal Action DisconnectClientAction;
public Action newClientAction; public Action newClientAction;
@@ -89,7 +90,7 @@ namespace Server.Models
/// send a message to all tcp clients in the list /// send a message to all tcp clients in the list
/// </summary> /// </summary>
/// <param name="message">the message to send</param> /// <param name="message">the message to send</param>
public void sendToAll(byte[] message) public async void sendToAll(byte[] message)
{ {
foreach (ServerClient sc in serverClients) foreach (ServerClient sc in serverClients)
{ {
@@ -97,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) public void SendToAllExcept(string username, byte[] message)
{ {
foreach (ServerClient sc in serverClients) foreach (ServerClient sc in serverClients)
@@ -105,6 +126,14 @@ 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) public void SendToLobby(Lobby lobby, byte[] message)
{ {
foreach (Lobby l in lobbies) foreach (Lobby l in lobbies)
@@ -113,6 +142,7 @@ namespace Server.Models
{ {
foreach (ServerClient sc in serverClientsInlobbies[l]) foreach (ServerClient sc in serverClientsInlobbies[l])
{ {
Debug.WriteLine("[SERVERCLIENT] Sending message");
sc.sendMessage(message); sc.sendMessage(message);
} }
break; break;
@@ -172,12 +202,18 @@ namespace Server.Models
return lobby.ID; 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) foreach (Lobby l in lobbies)
{ {
if (l.ID == id) if (l.ID == id)
{ {
if (l.Users.Count == 0)
{
user.Host = true;
isHost = true;
}
AddToLobby(l, user); AddToLobby(l, user);
Debug.WriteLine($"{user.Username} joined lobby with id {id}"); Debug.WriteLine($"{user.Username} joined lobby with id {id}");
break; break;

View File

@@ -6,6 +6,16 @@
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="resources\WordsForGame.json" />
</ItemGroup>
<ItemGroup>
<Content Include="resources\WordsForGame.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" /> <PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" /> <PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />

View File

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

@@ -1,9 +1,11 @@
using Client; using Client;
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -15,6 +17,7 @@ namespace SharedClientServer
public const byte MESSAGE = 0x02; public const byte MESSAGE = 0x02;
public const byte LOBBY = 0x03; public const byte LOBBY = 0x03;
public const byte CANVAS = 0x04; public const byte CANVAS = 0x04;
public const byte RANDOMWORD = 0x05;
public enum LobbyIdentifier public enum LobbyIdentifier
{ {
@@ -133,9 +136,16 @@ namespace SharedClientServer
return dynamicAsObject.ToObject<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.ASCII.GetString(json));
return payload.host;
} }
#endregion #endregion
@@ -159,7 +169,39 @@ namespace SharedClientServer
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4); Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4);
return res; return res;
} }
/*
* This method sends a random word from the json file, this happens when the client joins a lobby.
*/
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;
}
} }
} }