2 Commits

Author SHA1 Message Date
Sem van der Hoeven
c150bf3611 [FIX] fixed handling client disconnect 2020-10-21 22:54:37 +02:00
Sem van der Hoeven
e8a72e164f add try catch 2020-10-21 22:41:39 +02:00
3 changed files with 78 additions and 36 deletions

View File

@@ -6,6 +6,7 @@ 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;
@@ -45,7 +46,8 @@ 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)
@@ -87,6 +89,13 @@ namespace Server.Models
// 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);
}
}

View File

@@ -16,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;
@@ -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)
{
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)
{
foreach (Lobby l in lobbies)

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