Beispiel #1
0
        private async Task HandleSquareChangeRequest(SquareChangeRequest request)
        {
            var theSquare = _squares.First(sq => sq.Id == request.Id);

            theSquare.Color = request.Color;
            await SendSquaresToAll();
            await AnnounceSquareChange(request);
        }
Beispiel #2
0
        private async Task AnnounceSquareChange(SquareChangeRequest request)
        {
            var message = new SocketMessage <string>
            {
                MessageType = "announce",
                Payload     = $"{request.Name} has changed square #{request.Id} to {request.Color}"
            };

            await SendAll(message.ToJson());
        }
Beispiel #3
0
        public async Task AddUser(WebSocket socket)
        {
            try
            {
                var name = GenerateName();
                var userAddedSuccessfully = _users.TryAdd(name, socket);
                while (!userAddedSuccessfully)
                {
                    name = GenerateName();
                    userAddedSuccessfully = _users.TryAdd(name, socket);
                }

                GiveUserTheirName(name, socket).Wait();
                AnnounceNewUser(name).Wait();
                SendSquares(socket).Wait();
                while (socket.State == WebSocketState.Open)
                {
                    var buffer = new byte[1024 * 4];
                    WebSocketReceiveResult socketResponse;
                    var package = new List <byte>();
                    do
                    {
                        socketResponse = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        package.AddRange(new ArraySegment <byte>(buffer, 0, socketResponse.Count));
                    } while (!socketResponse.EndOfMessage);
                    var bufferAsString = System.Text.Encoding.ASCII.GetString(package.ToArray());
                    if (!string.IsNullOrEmpty(bufferAsString))
                    {
                        var changeRequest = SquareChangeRequest.FromJson(bufferAsString);
                        await HandleSquareChangeRequest(changeRequest);
                    }
                }
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            }
            catch (Exception ex)
            { }
        }