Exemplo n.º 1
0
        public async Task Initialize()
        {
            var buffer = new byte[1024 * 16];
            WebSocketReceiveResult wsresult = await socket.ReceiveAsync(new ArraySegment <byte>(buffer),
                                                                        CancellationToken.None);

            var initialMessage = System.Text.Encoding.Default.GetString(buffer);
            var parsedMessage  = JsonConvert.DeserializeObject <WebSocketMessage>(initialMessage);

            Array.Clear(buffer, 0, buffer.Length);
            while (parsedMessage.type != "init-host" && parsedMessage.type != "init-client")
            {
                var errorMessage = new BasicMessage()
                {
                    message = "Web socket was not initialized. Send initialization message first.", type = "error"
                };
                string serializedErrorMessage = JsonConvert.SerializeObject(errorMessage);
                await Send(serializedErrorMessage);

                wsresult = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                var message = System.Text.Encoding.Default.GetString(buffer);
                parsedMessage = JsonConvert.DeserializeObject <WebSocketMessage>(message);
                Array.Clear(buffer, 0, buffer.Length);
            }
            bool isClientSocket = parsedMessage.type == "init-client";

            OnOpen(this, parsedMessage.roomId, isClientSocket);
            while (!wsresult.CloseStatus.HasValue)
            {
                wsresult = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                if (wsresult.MessageType == WebSocketMessageType.Text)
                {
                    var receivedMessage = System.Text.Encoding.Default.GetString(buffer);
                    OnMessageReceived(this, receivedMessage);
                    Array.Clear(buffer, 0, buffer.Length);
                }
            }
            OnClose(this, parsedMessage.roomId);
            await socket.CloseAsync(wsresult.CloseStatus.Value, wsresult.CloseStatusDescription,
                                    CancellationToken.None);
        }
        public override async void handleNewMessage(AppWebSocket socket, string message)
        {
            var parsedMessage = JsonConvert.DeserializeObject <WebSocketMessage>(message);
            //WORKAROUND to fix problem with end of message
            var messageToSend = JsonConvert.SerializeObject(parsedMessage);

            if (_activeRooms.ContainsKey(parsedMessage.roomId))
            {
                var room = _activeRooms[parsedMessage.roomId];
                if (parsedMessage.type == "discussion")
                {
                    await room.HandleSendingMessage(socket, messageToSend);

                    if (!(parsedMessage.content["estimates"] is JArray estimates) || estimates.Count <= 1)
                    {
                        return;
                    }
                    var estimatesList = estimates.ToObject <List <WsEstimate> >()
                                        .OrderBy(e => e.estimate)
                                        .ToList();
                    var minEstimate = estimatesList.First();
                    var maxEstimate = estimatesList.Last();

                    var startDiscussionMessage =
                        new WebSocketMessage()
                    {
                        roomId   = parsedMessage.roomId,
                        type     = "start-discussion",
                        socketId = parsedMessage.socketId
                    };
                    var serializedDisussionMessage = JsonConvert.SerializeObject(startDiscussionMessage);

                    var minEstimates = estimatesList.Where(e => e.estimate == minEstimate.estimate).ToList();
                    minEstimates.ForEach(async e =>
                    {
                        try
                        {
                            await room.SendMessageToParticipant(e.socketId, serializedDisussionMessage);
                        }
                        catch (InvalidOperationException ex)
                        {
                            var errorString = "Error sending message to " + e.socketId + "; Socket not found." +
                                              ex.Message;
                            var errorMessage = new BasicMessage()
                            {
                                message = errorString, type = "error"
                            };
                            await socket.Send(errorMessage.ToJsonString());
                        }
                    });
                    if (minEstimate.estimate != maxEstimate.estimate)
                    {
                        var maxEstimates = estimatesList.Where(e => e.estimate == maxEstimate.estimate).ToList();
                        maxEstimates.ForEach(async e =>
                        {
                            try
                            {
                                await room.SendMessageToParticipant(e.socketId, serializedDisussionMessage);
                            }
                            catch (InvalidOperationException ex)
                            {
                                var errorString = "Error sending message to " + e.socketId + "; Socket not found." +
                                                  ex.Message;
                                var errorMessage = new BasicMessage()
                                {
                                    message = errorString, type = "error"
                                };
                                await socket.Send(errorMessage.ToJsonString());
                            }
                        }
                                             );
                    }
                }
                else if (parsedMessage.type == "chat")
                {
                    await room.SendMessageToOthers(socket.WebSocketId, messageToSend);
                }
                else
                {
                    try
                    {
                        await _activeRooms[parsedMessage.roomId].HandleSendingMessage(socket, messageToSend);
                    }
                    catch (WebSocketException ex)
                    {
                        await socket.Send(new BasicMessage { message = ex.Message, type = "error" }.ToJsonString());
                    }
                }
            }
            else
            {
                await socket.Send(new BasicMessage { message = "Room not found", type = "error" }.ToJsonString());
            }
        }