public DeviceServer(ProtocolFactory protocolFactory, IServiceProvider services, FanoutHub fanoutHub, IOptions <ProxyOptions> options, IOptions <SqlServerOptions> sqlOptions, ILogger <DeviceServer> logger) { _fanoutHub = fanoutHub; _options = options.Value; _logger = logger; var stackBuilder = new StackBuilder(services); if (sqlOptions.Value.ConnectionString != null) { stackBuilder.Use <SqlServerMiddleware>(); } var stack = stackBuilder.Build(); _protocol = protocolFactory.Create(_options.ProtocolName, stack); }
private void SymmetricListenerThread() { try { new SocketListener().Listen( ProtocolFactory .Create( "SymmetricProtocol")); } catch (NotSupportedException) { NotifyUIFactory .Create("ConsoleNotification") .SendMessageToUi( "Symmetric Protocol Thread : Failed Initialzing.", LogLevels.Critical, Colors.Crimson); } }
public async Task <int> HandleAsync() { var elapsedOnEntering = Program.Started.ElapsedMilliseconds; ILogger logger; if (Verbose) { var services = new ServiceCollection() .AddLogging(options => options.ClearProviders().AddConsole()) .Replace(ServiceDescriptor.Singleton(typeof(ILogger <>), typeof(TimedLogger <>))) .AddSingleton <ProtocolFactory>() .BuildServiceProvider(); logger = services.GetRequiredService <ILogger <ClientCommand> >(); } else { logger = new FakeLogger(); } logger.LogInformation("Booted after {ElapsedOnEntering}/{ElapsedMilliseconds}ms", elapsedOnEntering, Program.Started.ElapsedMilliseconds); using (var client = new TcpClient()) { try { var stopwatch = Stopwatch.StartNew(); if (Host != null) { // https://github.com/dotnet/corefx/issues/41588 if (Host == "localhost") { await client.ConnectAsync(IPAddress.Loopback, Port); } else { await client.ConnectAsync(Host, Port); } } else { await client.ConnectAsync(IPAddress.Loopback, Port); } var clientStream = client.GetStream(); // Dispose on the client disposes the stream logger.LogInformation("Connected in {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds); TaskCompletionSource <Packet> replyTcs = null; if (TimeoutMs != null) { var protocolFactory = new ProtocolFactory(logger); var protocol = protocolFactory.Create(ProtocolName, packet => { replyTcs.SetResult(packet); return(Task.CompletedTask); }); _ = Task.Run(() => protocol(client, default)); } var timeouts = 0; for (var sent = 0; sent < Count || Count == -1; sent++) { if (sent > 0) { await Task.Delay(TimeSpan.FromMilliseconds(Interval)); } stopwatch.Restart(); if (Filename is object) { using var file = File.OpenRead(Filename); await file.CopyToAsync(clientStream); await clientStream.FlushAsync(); } else { var data = GetDataBytes(); await clientStream.WriteAsync(data); await clientStream.FlushAsync(); } logger.LogInformation("Sent in {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds); if (TimeoutMs != null) { replyTcs = new TaskCompletionSource <Packet>(TaskCreationOptions.RunContinuationsAsynchronously); stopwatch.Restart(); await Task.WhenAny(replyTcs.Task, Task.Delay(TimeoutMs.Value)); if (replyTcs.Task.IsCompleted) { logger.LogInformation("Got reply after {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds); var replyTask = replyTcs.Task; var reply = await replyTask; Console.WriteLine(reply.ToString()); } else { logger.LogError("No reply received"); timeouts++; } } } if (timeouts > 0) { return(1); } } catch (SocketException e) when(e.SocketErrorCode == SocketError.ConnectionRefused) { logger.LogError("Unable to connect"); return(2); } } return(0); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using var remoteClient = new TcpClient(); var timeout = TimeSpan.Zero; try { _logger.LogInformation("Connecting to device on {RemoteHost}:{RemotePort}", _options.RemoteHost, _options.RemotePort); await remoteClient.ConnectAsync(_options.RemoteHost, _options.RemotePort); _logger.LogInformation("Connected to device on {RemoteClientRemoteEndpoint}", remoteClient.Client.RemoteEndPoint); _chatHub.RemoteClient = remoteClient; var stack = CreateStack(stoppingToken); var protocol = _protocolFactory.Create(_options.ProtocolName, stack); await protocol(remoteClient, stoppingToken); _logger.LogInformation("Connection to device on {RemoteClientRemoteEndpoint} was closed", remoteClient.Client.RemoteEndPoint); } catch (SocketException e) when(e.SocketErrorCode == SocketError.ConnectionRefused) { // Unable to connect to server _logger.LogWarning("Unable to connect to device server, retrying in one second"); // Retry in a second timeout = TimeSpan.FromMilliseconds(1000); } catch (SocketException e) { // Some other socket exception _logger.LogError(e, "Got exception while being connected to device"); timeout = TimeSpan.FromMilliseconds(500); } catch (Exception e) { _logger.LogError(e, "Unknown error"); timeout = TimeSpan.FromMilliseconds(500); } if (timeout > TimeSpan.Zero) { await Task.Delay(timeout, stoppingToken); } } catch (OperationCanceledException) when(stoppingToken.IsCancellationRequested) { } } _logger.LogInformation("Exiting chat connection service"); }