/// <summary> /// Handles a new socket connection, and begins the verification process before talking back and forth with the socket /// </summary> /// <param name="context">The http context that the socket connected through</param> /// <param name="socket">The socket attempting to get accepted</param> public async Task HandleNewSocketAsync(HttpContext context, WebSocket socket) { byte[] buf = new byte[4096]; //check nulls if (socket == null) { throw new ArgumentNullException(nameof(socket)); } //declare temptorary buffer ArraySegment <byte> buffer = new ArraySegment <byte>(buf); //temporary receive result WebSocketReceiveResult res = await socket .ReceiveAsync(buffer, CancellationToken.None) .ConfigureAwait(true); long playerId = 0; //check the message type if (!res.CloseStatus.HasValue) { string key = string.Empty; key = Encoding.UTF8.GetString(new ArraySegment <byte>(buf, 0, res.Count).Array); //check nulls if (string.IsNullOrEmpty(key)) { return; } //TODO under dosent work so this is a quick fix. think it something about empty chars at end key = key.Split("\"")[1]; //verify the user PlayerVerificationResponseModel playerData = await gameController .VerifyAsync(key).ConfigureAwait(false); //check nulls if (playerData == null || playerData.PlayerId.Equals(0)) { // Verification failed var encoded = Encoding.UTF8.GetBytes("{\"Authentication\":\"Error\"}"); var buffers = new ArraySegment <Byte>(encoded, 0, encoded.Length); await socket.SendAsync(buffers, WebSocketMessageType.Text, true, CancellationToken.None) .ConfigureAwait(false); return; } else { // Verification success var encoded = Encoding.UTF8.GetBytes("{\"Authentication\":\"Success\"}"); var buffers = new ArraySegment <Byte>(encoded, 0, encoded.Length); await socket.SendAsync(buffers, WebSocketMessageType.Text, true, CancellationToken.None) .ConfigureAwait(false); } playerId = playerData.PlayerId; //accept the player socket and add it to the gamecontroller list of players await gameController .AcceptPlayerAsync(new Player(playerData.Key, socket, playerData.PlayerId, playerData.Name)) .ConfigureAwait(false); } //keep receiving data while the socket is open while (!res.CloseStatus.HasValue) { //accept text only as of now //TODO: swap to binary? if (res.MessageType.Equals(WebSocketMessageType.Text)) { //get the string content and skip if that content turns out to be null string message = Encoding.UTF8.GetString(buffer[0..res.Count]).Trim();