Merge branch 'master' into stateful-canvas

This commit is contained in:
SemvdH
2020-10-22 22:30:42 +02:00
committed by GitHub
9 changed files with 736 additions and 569 deletions

View File

@@ -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;
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,24 +52,37 @@ namespace Client
private void OnConnect(IAsyncResult ar)
{
Debug.Write("finished connecting to server");
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)
{
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
try
{
int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 2048)
{
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 expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
@@ -76,15 +93,19 @@ namespace Client
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);
}
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (IOException e)
{
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke();
}
}
private void handleData(byte[] message)
@@ -165,10 +186,18 @@ namespace Client
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();
}
}
}

View File

@@ -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,8 +90,6 @@ 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)

View File

@@ -1,5 +1,5 @@
using Client.Views;
using Client.Views;
using GalaSoft.MvvmLight.Command;
using SharedClientServer;
using System;
@@ -9,6 +9,7 @@ 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;
@@ -32,6 +33,12 @@ namespace Client.ViewModels
private dynamic _payload;
public static string Word
{
get;
set;
}
public string _username;
public string _message;
@@ -206,6 +213,10 @@ namespace Client.ViewModels
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
@@ -213,13 +224,21 @@ namespace Client.ViewModels
Messages.Add($"{username}: {message}");
});
}
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
public void LeaveGame(object sender, CancelEventArgs e)
{
Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
}
/*
* MISC make this a callback
* Handles the random word that has been received from the server.
*/
public static void HandleRandomWord(string randomWord)
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Word = "NegerPik";
}
}
}

View File

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

View File

@@ -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,6 +25,7 @@ namespace Server.Models
private int totalBufferReceived = 0;
public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE;
private Callback OnMessageReceivedOk;
/// <summary>
@@ -86,12 +90,13 @@ 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);
}
@@ -108,9 +113,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:
@@ -145,7 +150,7 @@ namespace Server.Models
case JSONConvert.LOBBY:
// lobby data
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
handleLobbyMessage(payload,l);
handleLobbyMessage(payload, l);
break;
case JSONConvert.CANVAS:
@@ -190,6 +195,13 @@ namespace Server.Models
}
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>

View File

@@ -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;

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

@@ -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,4 +1,4 @@
using Client;
using Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
@@ -17,6 +17,8 @@ namespace SharedClientServer
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;
@@ -244,6 +246,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;
}
}
}