Skip to content

Commit

Permalink
attempt to disconnect socket when closing game or being rejected
Browse files Browse the repository at this point in the history
  • Loading branch information
BlastyTheDev committed Aug 18, 2024
1 parent affe161 commit d579a54
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 9 deletions.
39 changes: 32 additions & 7 deletions PolygonBazooka/Networking/Authentication.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
Expand All @@ -21,6 +22,9 @@ public Authentication()

public async Task<bool> LoginAsync(string username, string password, bool stayLoggedIn = false)
{
if (IsLoggedIn)
return true;

_stayLoggedIn = stayLoggedIn;

var clientHandler = new HttpClientHandler();
Expand All @@ -33,10 +37,19 @@ public async Task<bool> LoginAsync(string username, string password, bool stayLo
request.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);

HttpResponseMessage response;

try
{
response = await client.SendAsync(request);
}
catch (Exception)
{
return false;
}

var cookies = clientHandler.CookieContainer.GetCookies(new(uri));

foreach (Cookie cookie in cookies)
{
if (cookie.Name == "token")
Expand All @@ -51,22 +64,34 @@ public async Task<bool> LoginAsync(string username, string password, bool stayLo

public async Task<bool> RegisterAsync(string username, string password, string email, bool stayLoggedIn = false)
{
if (IsLoggedIn)
return true;

_stayLoggedIn = stayLoggedIn;

var clientHandler = new HttpClientHandler();
var client = new HttpClient(clientHandler);

string uri = "http://localhost:8080/api/auth/register";

var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StringContent(
$"{{\"username\":\"{username}\",\"password\":\"{password}\",\"email\":\"{email}\"}}",
Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);
HttpResponseMessage response;

try
{
response = await client.SendAsync(request);
}
catch (Exception)
{
return false;
}

var cookies = clientHandler.CookieContainer.GetCookies(new(uri));

foreach (Cookie cookie in cookies)
{
if (cookie.Name == "token")
Expand All @@ -91,7 +116,7 @@ public void Dispose()
{
if (!_stayLoggedIn)
Logout();
else
else if (IsLoggedIn)
File.WriteAllText("token.txt", Token.Value);
}
}
48 changes: 47 additions & 1 deletion PolygonBazooka/Networking/RankedSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ public class RankedSocket(PolygonBazookaGame game)
public const string LeaveQueue = "<LEAVEQUEUE>";
public const string Forfeit = "<FORFEIT>";

public const string ConnectionInitialized = "<INITIALIZED>";
public const string ConnectionRejected = "<REJECTED>";

public const string RequestDisconnect = "<DISCONNECT>";

public const string ChatPrefix = "MESSAGE:";

public const string MoveLeft = "l";
Expand All @@ -27,8 +32,21 @@ public class RankedSocket(PolygonBazookaGame game)

public ClientWebSocket Socket { get; private set; }

public bool Connected
{
get
{
if (Socket == null)
return false;
return Socket.State == WebSocketState.Open;
}
}

public async Task ConnectAsync()
{
if (!game.Authentication.IsLoggedIn)
return;

string uri = "ws://localhost:8080/api/ws/ranked";

Socket = new ClientWebSocket();
Expand All @@ -37,11 +55,28 @@ public async Task ConnectAsync()

clientWebSocketOptions.SetRequestHeader("Cookie", "token=" + game.Authentication.Token.Value);

await Socket.ConnectAsync(new(uri), CancellationToken.None);
try
{
await Socket.ConnectAsync(new(uri), CancellationToken.None);
}
catch (Exception)
{
return;
}

Console.WriteLine("wait");
var result = await ReceiveAsync();
Console.WriteLine("res" + result);

if (result != ConnectionInitialized)
await DisconnectAsync();
}

public async Task<string> ReceiveAsync()
{
if (!Connected)
return null;

var buffer = new byte[4096];
var segment = new ArraySegment<byte>(buffer);

Expand All @@ -60,16 +95,27 @@ public async Task<string> ReceiveAsync()

public async Task DisconnectAsync()
{
if (!Connected)
return;

await SendAsync(RequestDisconnect);

await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "disconnect", CancellationToken.None);
}

public async Task ChatAsync(string message)
{
if (!Connected)
return;

await SendAsync(ChatPrefix + message);
}

public async Task SendAsync(string message)
{
if (!Connected)
return;

byte[] messageBytes = Encoding.UTF8.GetBytes(message);
var messageSegment = new ArraySegment<byte>(messageBytes);

Expand Down
2 changes: 2 additions & 0 deletions PolygonBazooka/PolygonBazookaGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ protected override void Draw(GameTime gameTime)
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);

RankedSocket.DisconnectAsync().Wait();

Preferences.Save();
Authentication.Dispose();
Expand Down
3 changes: 2 additions & 1 deletion PolygonBazooka/Screens/MainMenuScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ private void UpdateMultiplayerMenu(GameTime gameTime, MouseState mouseState, Rec

if (_rankedButtonHovered)
{
_game.LoadScreen(ScreenName.RankedMenu);
// _game.LoadScreen(ScreenName.RankedMenu);
_game.ChangeGameState(GameState.RankedPlaying);
}
}
}
Expand Down

0 comments on commit d579a54

Please sign in to comment.