Example #1
0
        protected async void Connect()
        {
            wsClient = new WebsocketService(TDAParameters.webSocketUrl);
            await wsClient.Connecting();

            errorMessage = "";
            StateHasChanged();
        }
Example #2
0
 public WebsocketController(WebsocketService websocketService,
                            ICompanyService companyService,
                            IStockService stockService)
 {
     _websocketService = websocketService;
     _companyService   = companyService;
     _stockService     = stockService;
 }
 public StockHostedService(
     ILogger <StockHostedService> logger,
     RealTimeStockService realTimeStockService,
     WebsocketService websocketService,
     IServiceProvider serviceProvider
     )
 {
     _logger = logger;
     _realTimeStockService = realTimeStockService;
     _websocketService     = websocketService;
     _serviceProvider      = serviceProvider;
 }
Example #4
0
        public AVLProcessingService(DatabaseService database, WebsocketService websockets)
        {
            Database   = database;
            Websockets = websockets;

            Syncromatics = new SyncromaticsAPI.SyncromaticsAPI("http://usfbullrunner.com", 3000);
            Routes       = new Dictionary <int, Route>();

            RouteProcessor = new RouteProcessor();
            Routes         = RouteProcessor.ProcessRoutes(Syncromatics.GetRoutesAsync().Result).Result;

            VehicleProcessor = new VehicleProcessor(this, Routes);
            //VehicleProcessor.Start();
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public async void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddControllers().AddNewtonsoftJson();

            WebsocketService     websocket    = new WebsocketService();
            DatabaseService      database     = new DatabaseService();
            AVLProcessingService syncromatics = new AVLProcessingService(database, websocket);

            services.AddSingleton(syncromatics);
            services.AddSingleton(database);
        }
 private void TimerElapsed(object sender, ElapsedEventArgs e)
 {
     try
     {
         WebsocketService websocketService = new WebsocketService();
         websocketService.Send(new WebsocketData()
         {
             Code    = 1,
             Clients = null,
             Data    = new
             {
                 CurrentDate = DateTime.Now.ToString("yyyyMMddhhmmssff")
             }
         }).Wait(2 * 1000);
     }
     catch (Exception ex)
     {
         Log.Instance.Error(ex, "Error on heartbeat");
     }
 }
Example #7
0
        public async Task StartAsync_Should_Setup_Connection_And_Listen_To_Observables()
        {
            var options       = _fixture.Create <DeConzOptions>();
            var websocketPort = _fixture.Create <int>();

            var disposableMock           = new Mock <IDisposable>();
            var reconnectionHappenedMock = new Mock <IObservable <ReconnectionInfo> >(MockBehavior.Strict);

            reconnectionHappenedMock.Setup(o => o.Subscribe(It.IsAny <IObserver <ReconnectionInfo> >())).Returns(disposableMock.Object).Verifiable();
            var disconnectionHappenedMock = new Mock <IObservable <DisconnectionInfo> >(MockBehavior.Strict);

            disconnectionHappenedMock.Setup(o => o.Subscribe(It.IsAny <IObserver <DisconnectionInfo> >())).Returns(disposableMock.Object).Verifiable();
            var messageReceivedMock = new Mock <IObservable <ResponseMessage> >(MockBehavior.Strict);

            messageReceivedMock.Setup(o => o.Subscribe(It.IsAny <IObserver <ResponseMessage> >())).Returns(disposableMock.Object).Verifiable();

            var clientMock = new Mock <IWebsocketClient>(MockBehavior.Strict);

            clientMock.SetupSet(c => c.Name                  = It.IsAny <string>()).Callback <string>(value => value.Should().Be("deCONZ"));
            clientMock.SetupSet(c => c.ReconnectTimeout      = It.IsAny <TimeSpan>()).Callback <TimeSpan?>(value => value.Should().Be(TimeSpan.FromMinutes(5)));
            clientMock.SetupSet(c => c.ErrorReconnectTimeout = It.IsAny <TimeSpan>()).Callback <TimeSpan?>(value => value.Should().Be(TimeSpan.FromSeconds(30)));
            clientMock.SetupGet(c => c.ReconnectionHappened).Returns(reconnectionHappenedMock.Object);
            clientMock.SetupGet(c => c.DisconnectionHappened).Returns(disconnectionHappenedMock.Object);
            clientMock.SetupGet(c => c.MessageReceived).Returns(messageReceivedMock.Object);
            clientMock.Setup(c => c.Start()).Returns(Task.CompletedTask).Verifiable();

            var clientFactoryMock = new Mock <IWebsocketClientFactory>(MockBehavior.Strict);

            clientFactoryMock.Setup(f => f.CreateClientAsync(null)).ReturnsAsync(clientMock.Object).Verifiable();

            var mediatorMock = new Mock <IMediator>(MockBehavior.Strict);

            var service = new WebsocketService(clientFactoryMock.Object, mediatorMock.Object, new NullLogger <WebsocketService>());

            // act
            await service.StartAsync(default);
        internal static async Task <WebsocketService> Create(
            Func <bool> isSecureConnectionSchemeFunc,
            Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> validateServerCertificateFunc,
            EventLoopScheduler eventLoopScheduler,
            IObserver <ConnectionStatus> observerConnectionStatus,
            MessageWebsocketRx messageWebSocketRx)
        {
            var tcpConnectionHandler = new TcpConnectionService(
                isSecureConnectionSchemeFunc: isSecureConnectionSchemeFunc,
                validateServerCertificateFunc: validateServerCertificateFunc,
                connectTcpClientFunc: ConnectTcpClient,
                ReadOneByteFromStream,
                //readOneByteFunc: (stream, bytes, cts) => RunOnScheduler(ReadOneByteFromStream(stream, bytes, cts), eventLoopScheduler),
                connectionStatusAction: ConnectionStatusAction,
                messageWebSocketRx.HasTransferSocketLifeCycleOwnership,
                tcpClient: messageWebSocketRx.TcpClient);

            var websocketServices = new WebsocketService(
                new WebsocketConnectionHandler(
                    tcpConnectionHandler,
                    new WebsocketParserHandler(
                        tcpConnectionHandler),
                    ConnectionStatusAction,
                    (stream, connectionStatusAction) =>
                    new WebsocketSenderHandler(
                        tcpConnectionHandler,
                        ConnectionStatusAction,
                        //WriteToStream
                        (stream, bytes, cts) => RunOnScheduler(WriteToStream(stream, bytes, cts), eventLoopScheduler),
                        messageWebSocketRx.ExcludeZeroApplicationDataInPong
                        )
                    )
                );

            await Task.CompletedTask;

            return(websocketServices);

            void ConnectionStatusAction(ConnectionStatus status, Exception?ex)
            {
                if (status is ConnectionStatus.Disconnected)
                {
                    observerConnectionStatus.OnCompleted();
                }

                if (status is ConnectionStatus.Aborted)
                {
                    observerConnectionStatus.OnError(
                        ex ?? new WebsocketClientLiteException("Unknown error."));
                }
                observerConnectionStatus.OnNext(status);
            }

            async Task <bool> WriteToStream(Stream stream, byte[] byteArray, CancellationToken ct)
            {
                await stream.WriteAsync(byteArray, 0, byteArray.Length, ct).ConfigureAwait(false);

                await stream.FlushAsync().ConfigureAwait(false);

                return(true);
            }

            async Task <int> ReadOneByteFromStream(Stream stream, byte[] byteArray, CancellationToken ct)
            {
                try
                {
                    return(await stream.ReadAsync(byteArray, 0, byteArray.Length, ct).ConfigureAwait(false));
                }
                catch (OperationCanceledException)
                {
                    return(-1);
                }
            }

            async Task ConnectTcpClient(TcpClient tcpClient, Uri uri)
            => await tcpClient
            .ConnectAsync(uri.Host, uri.Port)
            .ConfigureAwait(false);

            // Running sends and/or writes on the Event Loop Scheduler serializes them.
            async Task <T> RunOnScheduler <T>(Task <T> task, IScheduler scheduler)
            => await task.ToObservable().ObserveOn(scheduler);
        }
Example #9
0
        public Test_Websocket()
        {
            WebsocketService service = new WebsocketService("ws://127.0.0.1:8081", new WebsocketHandle());

            Console.ReadLine();
        }
Example #10
0
        public WebsocketMiddleware(RequestDelegate next, WebsocketService websocketService)
        {
            _next = next;

            _websocketService = websocketService;
        }