Beispiel #1
0
        /// <summary>
        /// Handles the incoming messages
        /// </summary>
        /// <returns></returns>
        public async Task HandleMessagesAsync()
        {
            while (WebsocketClient.State == WebSocketState.Open)
            {
                var stream = new MemoryStream();
                WebSocketReceiveResult receiveResult;
                do
                {
                    var buffer = WebSocket.CreateClientBuffer(1024, 16);
                    receiveResult = await WebsocketClient.ReceiveAsync(buffer, CancellationToken.None);

                    stream.Write(buffer.Array ?? Array.Empty <byte>(), buffer.Offset, receiveResult.Count);
                } while (!receiveResult.EndOfMessage);

                switch (receiveResult.MessageType)
                {
                case WebSocketMessageType.Close:
                    await DisposeAsync();

                    break;

                case WebSocketMessageType.Text:
                {
                    var message  = Encoding.UTF8.GetString(stream.ToArray());
                    var document = new XmlDocument();
                    try
                    {
                        document.LoadXml(message.Trim());
                    }
                    catch
                    {
                        return;
                    }

                    switch (document.DocumentElement?.Name)
                    {
                    case "stream:features":
                        await SendAuthentication();

                        break;

                    case "success":
                        await SendIqAsync("_xmpp_bind1");

                        break;

                    case "iq":
                        if (document.DocumentElement.GetAttribute("id").Equals("_xmpp_bind1"))
                        {
                            await SendIqAsync("_xmpp_session1");
                        }

                        if (document.DocumentElement.GetAttribute("id").Equals("_xmpp_session1"))
                        {
                            await SendPresenceAsync(new Presence
                                {
                                    Status     = "",
                                    SessionId  = "",
                                    Properties = new Dictionary <string, object>()
                                });
                        }

                        break;

                    case "message":
                        await HandleMessageAsync(document);

                        break;
                    }

                    var args = new MessageReceivedEventArgs
                    {
                        Raw      = message,
                        Document = document
                    };
                    MessageReceived?.Invoke(args);
                    break;
                }
                }
            }

            Debugger.Break();
        }