All the code
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using AspShogiSockets.Extensions;
|
||||
using Gameboard.Shogi.Api.ServiceModels.Messages;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading.Tasks;
|
||||
using Websockets.Repositories;
|
||||
using Websockets.ServiceModels.Messages;
|
||||
using Websockets.ServiceModels.Types;
|
||||
|
||||
namespace Websockets.Managers.ClientActionHandlers
|
||||
{
|
||||
public class JoinByCodeHandler : IActionHandler
|
||||
{
|
||||
private readonly ILogger<JoinByCodeHandler> logger;
|
||||
private readonly IGameboardRepository repository;
|
||||
private readonly ISocketCommunicationManager communicationManager;
|
||||
|
||||
public JoinByCodeHandler(
|
||||
ILogger<JoinByCodeHandler> logger,
|
||||
ISocketCommunicationManager communicationManager,
|
||||
IGameboardRepository repository)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.repository = repository;
|
||||
this.communicationManager = communicationManager;
|
||||
}
|
||||
|
||||
public async Task Handle(WebSocket socket, string json, string userName)
|
||||
{
|
||||
logger.LogInformation("Socket Request \n{0}\n", new[] { json });
|
||||
var request = JsonConvert.DeserializeObject<JoinByCode>(json);
|
||||
var joinGameResponse = await repository.PostJoinByCode(new PostJoinByCode
|
||||
{
|
||||
PlayerName = userName,
|
||||
JoinCode = request.JoinCode
|
||||
});
|
||||
|
||||
if (joinGameResponse.JoinSucceeded)
|
||||
{
|
||||
var gameName = (await repository.GetGame(joinGameResponse.GameName)).GameName;
|
||||
|
||||
// Other members of the game see a regular JoinGame occur.
|
||||
var response = new JoinGameResponse(ClientAction.JoinGame)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = gameName
|
||||
};
|
||||
var serialized = JsonConvert.SerializeObject(response);
|
||||
await communicationManager.BroadcastToGame(gameName, serialized);
|
||||
communicationManager.SubscribeToGame(socket, gameName, userName);
|
||||
|
||||
// But the player joining sees the JoinByCode occur.
|
||||
response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
{
|
||||
PlayerName = userName,
|
||||
GameName = gameName
|
||||
};
|
||||
serialized = JsonConvert.SerializeObject(response);
|
||||
await socket.SendTextAsync(serialized);
|
||||
}
|
||||
else
|
||||
{
|
||||
var response = new JoinGameResponse(ClientAction.JoinByCode)
|
||||
{
|
||||
PlayerName = userName,
|
||||
Error = "Error joining game."
|
||||
};
|
||||
var serialized = JsonConvert.SerializeObject(response);
|
||||
logger.LogInformation("Socket Response \n{0}\n", new[] { serialized });
|
||||
await socket.SendTextAsync(serialized);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user