2 Commits

Author SHA1 Message Date
Dogukan
4d3dda023c Merge branch 'master' into feature/handleChatData 2020-10-21 22:43:18 +02:00
Dogukan
d5d6d59690 [FIX] fixed the broadcast for the chat messages. 2020-10-21 22:40:36 +02:00
5 changed files with 61 additions and 85 deletions

View File

@@ -25,6 +25,7 @@ namespace Client
public Callback OnLobbiesReceivedAndWaitingForHost;
public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave;
private ClientData data = ClientData.Instance;
public Lobby[] Lobbies { get; set; }
public Client(string username)
@@ -82,6 +83,7 @@ namespace Client
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:
@@ -93,6 +95,11 @@ namespace Client
string textUsername = combo.Item1;
string textMsg = combo.Item2;
if(textUsername != data.User.Username)
{
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg);
}
//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);

View File

@@ -21,13 +21,13 @@ namespace Client.ViewModels
private Point currentPoint = new Point();
private Color color;
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
private dynamic _payload;
private string _username;
public string _username;
private string _message;
public string _message;
public string Message
{
get
@@ -121,6 +121,13 @@ namespace Client.ViewModels
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
}
public static void HandleIncomingMsg(string username, string message)
{
Application.Current.Dispatcher.Invoke(delegate
{
Messages.Add($"{username}: {message}");
});
}
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Leaving...");

View File

@@ -6,7 +6,6 @@ using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
using static SharedClientServer.JSONConvert;
@@ -46,56 +45,48 @@ namespace Server.Models
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return;
try
int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024)
{
int bytesReceived = this.stream.EndRead(ar);
throw new OutOfMemoryException("buffer is too small!");
}
if (totalBufferReceived + bytesReceived > 1024)
// 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)
{
throw new OutOfMemoryException("buffer is too small!");
}
break;
}
// 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;
}
}
// 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);
}
@@ -131,11 +122,15 @@ namespace Server.Models
string textUsername = combo.Item1;
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
serverCom.SendToLobby(ServerCommunication.INSTANCE.GetLobbyForUser(User),payload);
Debug.WriteLine("Payload has been sent!");
//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:

View File

@@ -16,7 +16,6 @@ namespace Server.Models
public bool Started = false;
public List<Lobby> lobbies;
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
internal Action DisconnectClientAction;
public Action newClientAction;
@@ -98,26 +97,6 @@ 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)
@@ -126,14 +105,6 @@ 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)

View File

@@ -33,10 +33,6 @@ 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));