示例#1
0
        public async Task Invoke(HttpContext context)
        {
            source = new CancellationTokenSource();
            if (context.Request.Method.ToUpperInvariant() == "POST")
            {
                //sending a message
                //adapter = ProtocolAdapterFactory.Create(config, context, source.Token);
                adapter = ProtocolAdapterFactory.Create(config, context, null, null, source.Token);
                adapter.Init();
            }
            else if (context.Request.Method.ToUpperInvariant() == "GET")
            {
                //long polling
                //adapter = ProtocolAdapterFactory.Create(config, context, source.Token);
                adapter            = ProtocolAdapterFactory.Create(config, context, null, null, source.Token);
                adapter.OnObserve += Adapter_OnObserve;
                adapter.Init();
                this.context = context;
                ThreadPool.QueueUserWorkItem(new WaitCallback(Listen), waitHandles[0]);
                WaitHandle.WaitAll(waitHandles);
                await adapter.Channel.CloseAsync();

                await _next(context);
            }
            else
            {
            }
        }
        public async Task <HttpResponseMessage> Get()
        {
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                try
                {
                    socket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                    adapter          = ProtocolAdapterFactory.Create(config, graphManager, HttpContext, socket, null, authn, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    await adapter.Channel.OpenAsync();

                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                catch (Exception ex)
                {
                    StatusCode(500);
                    Console.WriteLine(ex.Message);
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
示例#3
0
        public async Task Get()
        {
            
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                //string subprotocol = HttpContext.WebSockets.WebSocketRequestedProtocols[0];
                socket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                //socket = HttpContext.WebSockets.AcceptWebSocketAsync().GetAwaiter().GetResult();


                try
                {
                    //adapter = ProtocolAdapterFactory.Create(config, HttpContext, socket, authn, source.Token);
                    adapter = ProtocolAdapterFactory.Create(config, HttpContext, socket, null, authn, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    //StatusCode(101);
                    //return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
                }
                catch(Exception ex)
                {
                    StatusCode(500);
                    Console.WriteLine(ex.Message);
                    //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                }
            }
            else
            {
                //return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }
示例#4
0
        public async Task <HttpResponseMessage> Get()
        {
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                try
                {
                    socket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                    adapter = ProtocolAdapterFactory.Create(config, graphManager, HttpContext, socket, null, authn,
                                                            source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    await adapter.Channel.OpenAsync();

                    await logger.LogDebugAsync("Websocket channel open.");

                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                catch (Exception ex)
                {
                    StatusCode(500);
                    await logger.LogErrorAsync(ex, "WebSocket get - 500");

                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }

            await logger.LogWarningAsync($"WebSocket status code {HttpStatusCode.NotFound}");

            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
示例#5
0
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                return;
            }

            BasicAuthenticator basicAuthn = new BasicAuthenticator();

            SkunkLab.Security.Tokens.SecurityTokenType tokenType = Enum.Parse <SkunkLab.Security.Tokens.SecurityTokenType>(config.ClientTokenType, true);
            basicAuthn.Add(tokenType, config.ClientSymmetricKey, config.ClientIssuer, config.ClientAudience, context);
            IAuthenticator authn = basicAuthn;

            WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();

            source = new CancellationTokenSource();
            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, graphManager, context, socket, logger, authn, source.Token);

            container.Add(adapter.Channel.Id, adapter);
            adapter.OnClose += Adapter_OnClose;
            adapter.OnError += Adapter_OnError;
            adapter.Init();


            await adapter.Channel.OpenAsync();

            await _next(context);

            Console.WriteLine("Exiting WS Invoke");
        }
示例#6
0
        public HttpResponseMessage Get()
        {
            try
            {
                SkunkLab.Security.Authentication.BasicAuthenticator authn = new SkunkLab.Security.Authentication.BasicAuthenticator();

                HttpContext context = HttpContext.Current;

                if (context.IsWebSocketRequest ||
                    context.IsWebSocketRequestUpgrading)
                {
                    PiraeusConfig config = Piraeus.Configuration.PiraeusConfigManager.Settings;

                    adapter          = ProtocolAdapterFactory.Create(config, Request, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                else //long polling
                {
                    adapter            = ProtocolAdapterFactory.Create(config, Request, source.Token);
                    adapter.OnObserve += Adapter_OnObserve;
                    adapter.Init();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Listen), waitHandles[0]);
                    WaitHandle.WaitAll(waitHandles);

                    return(response);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
示例#7
0
        public async Task StartAsync()
        {
            listener.ExclusiveAddressUse = false;
            listener.DontFragment        = true;
            listener.Client.Bind(localEP);

            await logger.LogDebugAsync($"UDP Gateway started on {localEP.Address} and port {localEP.Port}");

            while (!token.IsCancellationRequested)
            {
                try
                {
                    UdpReceiveResult result = await listener.ReceiveAsync();

                    if (result.Buffer.Length > 0)
                    {
                        string key = CreateNamedKey($"{result.RemoteEndPoint.Address}:{result.RemoteEndPoint.Port}");
                        if (cache.Contains(key))
                        {
                            Tuple <ProtocolAdapter, CancellationTokenSource> tuple =
                                (Tuple <ProtocolAdapter, CancellationTokenSource>)cache.Get(key);
                            if (tuple != null && tuple.Item1 != null)
                            {
                                cache.Get(CreateNamedKey(tuple.Item1.Channel.Id));
                                if (tuple.Item1.Channel.State == ChannelState.Open)
                                {
                                    await tuple.Item1.Channel.AddMessageAsync(result.Buffer);
                                }
                            }
                        }
                        else
                        {
                            CancellationTokenSource cts     = new CancellationTokenSource();
                            ProtocolAdapter         adapter = ProtocolAdapterFactory.Create(config, graphManager, authn,
                                                                                            listener, result.RemoteEndPoint, logger, cts.Token);
                            string namedKey = CreateNamedKey(adapter.Channel.Id);
                            cache.Add(namedKey, key, GetCachePolicy(5.0 * 60.0));
                            cache.Add(key, new Tuple <ProtocolAdapter, CancellationTokenSource>(adapter, cts),
                                      GetCachePolicy(5.0 * 60.0));

                            adapter.OnError   += Adapter_OnError;
                            adapter.OnClose   += Adapter_OnClose;
                            adapter.OnObserve += Adapter_OnObserve;
                            await adapter.Channel.OpenAsync();

                            adapter.Init();
                            await adapter.Channel.AddMessageAsync(result.Buffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogErrorAsync(ex, "Fault UDP listener.");
                    throw ex;
                }
            }
        }
示例#8
0
 public HttpResponseMessage Post()
 {
     context          = HttpContext;
     source           = new CancellationTokenSource();
     adapter          = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
     adapter.OnClose += Adapter_OnClose;
     adapter.Init();
     return(new HttpResponseMessage(HttpStatusCode.Accepted));
 }
示例#9
0
        private void ManageConnection(TcpClient client)
        {
            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, client, logger, token);

            dict.Add(adapter.Channel.Id, adapter);
            adapter.OnError += Adapter_OnError;
            adapter.OnClose += Adapter_OnClose;
            adapter.Init();
            adapter.Channel.OpenAsync().LogExceptions();
            adapter.Channel.ReceiveAsync().LogExceptions();
        }
示例#10
0
        public async Task StartAsync()
        {
            UdpClient listener = new UdpClient();

            listener.ExclusiveAddressUse = false;
            listener.DontFragment        = true;
            listener.Client.Bind(localEP);

            Console.WriteLine("UDP listener initialized on port {0}", localEP.Port);

            while (!token.IsCancellationRequested)
            {
                try
                {
                    UdpReceiveResult result = await listener.ReceiveAsync();

                    if (result.Buffer.Length > 0)
                    {
                        string key = String.Format("{0}:{1}", result.RemoteEndPoint.Address.ToString(), result.RemoteEndPoint.Port);

                        if (!cache.ContainsKey(key))
                        {
                            CancellationTokenSource cts = new CancellationTokenSource();
                            //ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, listener, result.RemoteEndPoint, cts.Token);
                            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, listener, result.RemoteEndPoint, null, cts.Token);
                            adapter.OnError += Adapter_OnError;
                            adapter.OnClose += Adapter_OnClose;
                            await adapter.Channel.OpenAsync();

                            container.Add(adapter.Channel.Id, key);
                            cache.Add(key, new Tuple <ProtocolAdapter, CancellationTokenSource>(adapter, cts));
                            adapter.Init();
                            await adapter.Channel.AddMessageAsync(result.Buffer);
                        }
                        else
                        {
                            Tuple <ProtocolAdapter, CancellationTokenSource> tuple = cache[key];
                            if (tuple.Item1.Channel.State == ChannelState.Open)
                            {
                                await tuple.Item1.Channel.AddMessageAsync(result.Buffer);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new ServerFailedEventArgs("UDP", localEP.Port));
                    //await Log.LogErrorAsync("UDP server channel error {0}", ex.Message);
                }
            }
        }
示例#11
0
 public HttpResponseMessage Post()
 {
     try
     {
         adapter          = ProtocolAdapterFactory.Create(config, Request, source.Token);
         adapter.OnClose += Adapter_OnClose;
         adapter.Init();
         return(new HttpResponseMessage(HttpStatusCode.Accepted));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
     }
 }
示例#12
0
        public IActionResult Get()
        {
            context            = HttpContext;
            source             = new CancellationTokenSource();
            adapter            = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
            adapter.OnObserve += Adapter_OnObserve;
            adapter.Init();
            ThreadPool.QueueUserWorkItem(Listen, waitHandles[0]);
            WaitHandle.WaitAll(waitHandles);
            Task task = adapter.Channel.CloseAsync();

            Task.WhenAll(task);
            Response.Headers.Add("x-sl-resource", longpollResource);
            Response.ContentLength = longpollValue.Length;
            Response.ContentType   = contentType;
            ReadOnlyMemory <byte> rom = new ReadOnlyMemory <byte>(longpollValue);

            Response.BodyWriter.WriteAsync(rom);
            return(StatusCode(200));
        }
示例#13
0
        public async Task Invoke(HttpContext context)
        {
            source             = new CancellationTokenSource();
            adapter            = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
            adapter.OnObserve += Adapter_OnObserve;
            adapter.OnClose   += Adapter_OnClose;
            adapter.Init();
            await next(context);

            if (context.Request.Method.ToUpperInvariant() == "GET")
            {
                //long polling
                //adapter = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);

                //adapter.Init();
                this.context = context;
                ThreadPool.QueueUserWorkItem(Listen, waitHandles[0]);
                WaitHandle.WaitAll(waitHandles);
                //adapter.Dispose();
            }

            await Task.CompletedTask;
        }
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                return;
            }

            BasicAuthenticator basicAuthn = new BasicAuthenticator();

            SkunkLab.Security.Tokens.SecurityTokenType tokenType = Enum.Parse <SkunkLab.Security.Tokens.SecurityTokenType>(config.ClientTokenType, true);
            basicAuthn.Add(tokenType, config.ClientSymmetricKey, config.ClientIssuer, config.ClientAudience, context);
            IAuthenticator authn = basicAuthn;

            socket = await context.WebSockets.AcceptWebSocketAsync();

            source = new CancellationTokenSource();
            //adapter = ProtocolAdapterFactory.Create(config, context, socket, authn, source.Token);
            adapter          = ProtocolAdapterFactory.Create(config, context, socket, null, authn, source.Token);
            adapter.OnClose += Adapter_OnClose;
            adapter.OnError += Adapter_OnError;
            adapter.Init();

            await adapter.Channel.OpenAsync();  //blocking until closed
        }