[FIX] handled disconnects for everything

This commit is contained in:
Sem van der Hoeven
2020-10-22 17:00:26 +02:00
parent 07b0357b0a
commit eca17cc70f
2 changed files with 49 additions and 27 deletions

View File

@@ -2,8 +2,10 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using static SharedClientServer.JSONConvert;
namespace Client
@@ -23,6 +25,7 @@ namespace Client
public Callback OnLobbiesListReceived;
public Callback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect;
public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave;
private ClientData data = ClientData.Instance;
@@ -39,18 +42,27 @@ 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 > 1024)
@@ -78,6 +90,12 @@ namespace Client
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)

View File

@@ -35,6 +35,10 @@ namespace Client
client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies;
client.OnLobbyLeave = leaveLobby;
client.OnServerDisconnect = () =>
{
Environment.Exit(0);
};
OnHostButtonClick = new RelayCommand(hostGame);