Exemplo n.º 1
0
        public async Task SendStream(WebNotifyConnection connection, Stream stream)
        {
            stream.Position = 0;
            var bufferLength = 8 * 1024;
            var buffer       = new byte[bufferLength];
            var count        = 0;

            connection.SendingCount++;
            using (var timeout = new CancellationTokenSource(5000))
            {
                while ((count = stream.Read(buffer, 0, bufferLength)) > 0)
                {
                    await connection.Socket.SendAsync(new ArraySegment <byte>(buffer, 0, count)
                                                      , WebSocketMessageType.Binary
                                                      , stream.Position == stream.Length
                                                      , timeout.Token);

                    if (timeout.IsCancellationRequested)
                    {
                        throw new TimeoutException($"Timeout of sending message {Helper.LenghtFormat(stream.Length)}");
                    }
                    timeout.CancelAfter(5000);
                }
            }
            connection.SendCount++;
            connection.SendLength += stream.Length;
#if DEBUG
            Debug.WriteLine($"Send Message {DateTime.UtcNow} Length: {stream.Length} ");
#endif
        }
Exemplo n.º 2
0
 public async Task SendObject(WebNotifyConnection connection, object data)
 {
     using (var stream = WriteData(data, connection.User))
     {
         await SendStream(connection, stream);
     }
 }
Exemplo n.º 3
0
        public async Task CloseAsync(WebNotifyConnection connection)
        {
            if (connection != null)
            {
                await connection.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Internal Server Close.", CancellationToken.None);

                Remove(connection);
            }
        }
Exemplo n.º 4
0
        public async Task SendText(WebNotifyConnection connection, string text)
        {
            var buffer = System.Text.Encoding.UTF8.GetBytes(text);

            using (var stream = new MemoryStream(buffer))
            {
                await SendStream(connection, stream);
            }
        }
Exemplo n.º 5
0
        protected object LoadMessage(WebNotifyConnection connection, MemoryStream stream)
        {
            stream.Position = 0;
            var jsonOptions = new JsonSerializerOptions();

            jsonOptions.InitDefaults(new DBItemConverterFactory {
                CurrentUser = connection.User
            });
            var span     = new ReadOnlySpan <byte>(stream.GetBuffer(), 0, (int)stream.Length);
            var property = (string)null;
            var type     = (Type)null;
            var obj      = (object)null;

            connection.ReceiveCount++;
            connection.ReceiveLength += stream.Length;
            var jreader = new Utf8JsonReader(span);

            {
                while (jreader.Read())
                {
                    switch (jreader.TokenType)
                    {
                    case JsonTokenType.PropertyName:
                        property = jreader.GetString();
                        break;

                    case JsonTokenType.String:
                        switch (property)
                        {
                        case ("Type"):
                            type = TypeHelper.ParseType(jreader.GetString());
                            break;
                        }
                        break;

                    case JsonTokenType.StartObject:
                        if (string.Equals(property, "Value", StringComparison.Ordinal) && type != null)
                        {
                            property = null;
                            obj      = JsonSerializer.Deserialize(ref jreader, type, jsonOptions);
                        }
                        break;
                    }
                }
            }
#if DEBUG
            Debug.WriteLine($"Receive Message {DateTime.UtcNow} Length: {stream.Length} ");
#endif
            stream.Dispose();
            return(obj);
        }
Exemplo n.º 6
0
        public virtual WebNotifyConnection Register(WebSocket socket, IUserIdentity user, string address)
        {
            var connection = GetBySocket(socket);

            if (connection == null)
            {
                connection = new WebNotifyConnection
                {
                    Socket  = socket,
                    User    = user,
                    Address = address,
                };
                connections.Add(connection);
            }
            return(connection);
        }
Exemplo n.º 7
0
        protected virtual async Task <object> OnMessageReceive(WebNotifyConnection connection, MemoryStream stream)
        {
            await Task.Delay(10).ConfigureAwait(false);

            object obj = LoadMessage(connection, stream);

            if (obj is WebNotifyRegistration registration)
            {
                connection.Platform     = registration.Platform;
                connection.Application  = registration.Application;
                connection.Version      = registration.Version;
                connection.VersionValue = Version.TryParse(connection.Version, out var version) ? version : new Version("1.0.0.0");
            }
            ReceiveMessage?.Invoke(this, new WebNotifyEventArgs(connection, obj));
            return(obj);
        }
Exemplo n.º 8
0
        //https://github.com/radu-matei/websocket-manager/blob/blog-article/src/WebSocketManager/WebSocketManagerMiddleware.cs
        public async Task ListenAsync(WebNotifyConnection connection)
        {
            var buffer = new ArraySegment <byte>(new byte[8192]);

            while (CheckConnection(connection))
            {
                try
                {
                    WebSocketReceiveResult result = null;
                    var stream = new MemoryStream();
                    do
                    {
                        result = await connection.Socket.ReceiveAsync(buffer, CancellationToken.None);

                        if (result.Count > 0)
                        {
                            stream.Write(buffer.Array, buffer.Offset, result.Count);
                        }
                    }while (!result.EndOfMessage);

                    switch (result.MessageType)
                    {
                    case WebSocketMessageType.Binary:
                    case WebSocketMessageType.Text:
                        _ = OnMessageReceive(connection, stream);
                        break;

                    case WebSocketMessageType.Close:
                        stream.Dispose();
                        await connection.Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Good luck!", CancellationToken.None);

                        Remove(connection);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Helper.OnException(ex);
                }
            }
            Remove(connection);
        }
Exemplo n.º 9
0
        public virtual bool Remove(WebNotifyConnection connection)
        {
            var removed = false;

            try
            {
                if ((removed = connections.Remove(connection)))
                {
                    Debug.WriteLine($"Remove webSocket from {connection?.UserEmail}");
                    connection?.Dispose();
                }
            }
            catch (Exception ex)
            {
                Helper.OnException(ex);
            }

            RemoveConnection?.Invoke(this, new WebNotifyEventArgs(connection));
            return(removed);
        }
Exemplo n.º 10
0
 public WebNotifyEventArgs(WebNotifyConnection client, string message = null)
 {
     Client  = client;
     Message = message;
 }
Exemplo n.º 11
0
 public WebNotifyEventArgs(WebNotifyConnection client, object data) : this(client, null)
 {
     Data = data;
 }
Exemplo n.º 12
0
 public bool CheckConnection(WebNotifyConnection connection)
 {
     return(connection?.Socket != null &&
            (connection.State == WebSocketState.Open ||
             connection.State == WebSocketState.Connecting));
 }