public void SocketConfiguration_applied_to_TcpSocket_when_connecting(NodeType nodeType, bool hasReceiveTimeout) { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { ConnectTimeout = TimeSpan.FromSeconds(5), SendBufferSize = 128, ReceiveBufferSize = 256, SendTimeout = TimeSpan.FromSeconds(1), ReceiveTimeout = TimeSpan.FromSeconds(2) }; var server = new TcpListener(IPAddress.Loopback, endpoint.Port); server.Start(); try { server.AcceptTcpClientAsync(); var socket = (TcpSocket) new SocketFactory().CreateAndConnectAsync(endpoint, nodeType, socketConfiguration); Assert.AreEqual(socketConfiguration.SendBufferSize, socket.TcpClient.SendBufferSize); Assert.AreEqual(socketConfiguration.ReceiveBufferSize, socket.TcpClient.ReceiveBufferSize); Assert.AreEqual(socketConfiguration.SendTimeout.ToMillisOrZero(), socket.TcpClient.SendTimeout); var expectedReceiveTimeout = hasReceiveTimeout ? socketConfiguration.ReceiveTimeout.ToMillisOrZero() : 0; Assert.AreEqual(expectedReceiveTimeout, socket.TcpClient.ReceiveTimeout); } finally { server.Stop(); } }
private protected Message(SocketConfiguration configuration, TMessage message) { Content = message; _configuration = configuration; _serializer = configuration.Serializer; Payload = _serializer.Serialize <TMessage>(Content); }
private static ContainerBuilder PopulateServices(ContainerBuilder builder) { builder.RegisterType <MainForm>().SingleInstance(); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false) .Build(); builder.RegisterInstance(config) .As <IConfiguration>() .SingleInstance() .ExternallyOwned(); var vivotekConfig = new CameraConfigModel(); config.GetSection("cameras").Bind(vivotekConfig); builder.RegisterInstance(vivotekConfig) .As <CameraConfigModel>() .SingleInstance() .ExternallyOwned(); var socketsConfig = new SocketConfiguration(); config.GetSection("socketClient").Bind(socketsConfig); builder.RegisterInstance(socketsConfig) .As <SocketConfiguration>() .SingleInstance() .ExternallyOwned(); builder.RegisterType <LoggerFactory>() .As <ILoggerFactory>() .SingleInstance(); builder.RegisterGeneric(typeof(Logger <>)) .As(typeof(ILogger <>)) .SingleInstance(); // SetupRabbitMqConnection(builder, config); // SetupRabbitMqEventBus(builder, config); builder.AddSocketClientConnection(socketsConfig); builder.AddSocketClientEventBus(); builder.RegisterGeneric(typeof(ExponentialGamepadProcessor <,>)) .As(typeof(IGamepadProcessor <,>)) .InstancePerDependency(); builder.RegisterType <CyclicTimer>() .InstancePerDependency(); builder.RegisterType <GStreamerLauncher>() .SingleInstance(); builder.RegisterType <VivotekDomeCameraController>() .InstancePerDependency(); return(builder); }
public EasyServer(ILogger <EasyServer> logger = null, IConfiguration config = null) { _logger = logger; _config = config; try { if (config != null) { EasyServerConfiguration = config.GetSection("EasyServer").Get <EasyServerConfiguration>(); SocketConfiguration = config.GetSection("EasyServer").GetSection("EasySocket").Get <SocketConfiguration>(); } else { EasyServerConfiguration = new EasyServerConfiguration(); SocketConfiguration = new SocketConfiguration(); } Initialize(EasyServerConfiguration.MaxConnection); } catch (Exception exception) { throw new Exception("Failed to initialize easy server...", exception); } }
public async Task StartAsync() { var config = new SocketConfiguration { Ip = Ip, Port = Port }; clientStream = new RecoverableEventMessageStream <SimpleMessage>( TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(2), 3, disconnectionEvent => new EventMessageStream <SimpleMessage>( Deserializer, Serializer, new SocketDuplexMessageStreamWrapper(config), HandleClientMessage, HandleClientKeepAlive, disconnectionEvent ), async stream => { await Task.Delay(10).ConfigureAwait(false); }, stream => new ValueTask(), HandleClientDisconnection ); await clientStream.OpenAsync().ConfigureAwait(false); }
public ScaleOutListenerTests() { tokenSource = new CancellationTokenSource(); frontEndSocket = new Mock <ISocket>(); socketFactory = new Mock <ISocketFactory>(); socketFactory.Setup(m => m.CreateRouterSocket()).Returns(frontEndSocket.Object); socketConfig = new SocketConfiguration(); socketFactory.Setup(m => m.GetSocketConfiguration()).Returns(socketConfig); performanceCounterManager = new Mock <IPerformanceCounterManager <KinoPerformanceCounters> >(); var perfCounter = new Mock <IPerformanceCounter>(); performanceCounterManager.Setup(m => m.GetCounter(It.IsAny <KinoPerformanceCounters>())).Returns(perfCounter.Object); logger = new Mock <ILogger>(); localRouterSocket = new Mock <ILocalSendingSocket <IMessage> >(); scaleOutConfigurationManager = new Mock <IScaleOutConfigurationManager>(); scaleOutAddresses = new[] { new SocketEndpoint("tcp://127.0.0.1:8080"), new SocketEndpoint("tcp://127.0.0.2:9090") }; scaleOutConfigurationManager.Setup(m => m.GetScaleOutAddressRange()).Returns(scaleOutAddresses); scaleOutConfigurationManager.Setup(m => m.GetScaleOutReceiveMessageQueueLength()).Returns(1000); securityProvider = new Mock <ISecurityProvider>(); scaleOutListener = new ScaleOutListener(socketFactory.Object, localRouterSocket.Object, scaleOutConfigurationManager.Object, securityProvider.Object, performanceCounterManager.Object, logger.Object); }
public void SendReceiveAndVerify_keeps_SendTimeout_ReceiveTimeout() { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { SendTimeout = TimeSpan.FromSeconds(10), ReceiveTimeout = TimeSpan.FromSeconds(20) }; var server = new TcpListener(IPAddress.Loopback, endpoint.Port); server.Start(); try { server.AcceptTcpClientAsync(); var nodeGreetingVerifier = new NodeGreetingMessageVerifier(NodeType.Requester, NodeType.Responder); var socket = (TcpSocket) new SocketFactory().CreateAndConnectAsync(endpoint, NodeType.Responder, socketConfiguration); Assert.Throws <TimeoutException>(() => nodeGreetingVerifier.SendReceiveAndVerify(socket, TimeSpan.FromSeconds(2))); Assert.AreEqual(socketConfiguration.SendTimeout.ToMillisOrZero(), socket.TcpClient.SendTimeout); Assert.AreEqual(socketConfiguration.ReceiveTimeout.ToMillisOrZero(), socket.TcpClient.ReceiveTimeout); } finally { server.Stop(); } }
public BaseSocket(ILogger logger, SocketConfiguration socketConfig) { _logger = logger; SocketConfiguration = socketConfig; ReceiveSocketAsyncEventArgs.SetBuffer(new byte[SocketConfiguration.ReceiveBufferSize], 0, SocketConfiguration.ReceiveBufferSize); ReceiveSocketAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(CompleteReadWriteEvent); }
private static void Main(/*string[] args*/) { Console.WriteLine("SocketClientApp is running..."); MessageDistributer.Instance.AddObserver(new ConsoleWriter()); var hostName = Dns.GetHostName(); var socketConfiguration = new SocketConfiguration(hostName, 3333); var tcpClient = socketConfiguration.CreateTcpClient(); var clientListener = new TcpClientListener(tcpClient); clientListener.StartAsync(); for (int i = 0; i < 10; i++) { Message message = new Message() { From = "Geri", Body = DateTime.Now.ToString() }; clientListener.Write(message); System.Threading.Thread.Sleep(1000); } Message exitMsg = new Message() { Command = SocketCommand.Quit.ToString(), From = "Geri", Body = string.Empty }; clientListener.Write(exitMsg); //var json = JsonSerializer.Serialize<Message>(message); //var bytes = Encoding.ASCII.GetBytes(json); //var stream = client.GetStream(); //stream.Write(bytes, 0, bytes.Length); //stream.Flush(); ////Thread.Sleep(2000); ////stream.Close(); ////using var stream1 = client.GetStream(); //stream.Write(bytes, 0, bytes.Length); //stream.Flush(); ////Thread.Sleep(2000); ////stream1.Close(); //message.Command = SocketCommand.Quit.ToString(); //json = JsonSerializer.Serialize<Message>(message); //bytes = Encoding.ASCII.GetBytes(json); ////using var stream2 = client.GetStream(); //stream.Write(bytes, 0, bytes.Length); //stream.Flush(); ////Thread.Sleep(2000); ////stream2.Close(); //stream.Close(); //client.Close(); }
internal static async Task RunReqRep(SocketConfiguration configuration) { using var rqRep = new RqRep(configuration); SetupResponder(rqRep); System.Console.WriteLine("try request"); await RequestAndWriteResultAsync(rqRep); }
internal static async Task UseBusInterface(SocketConfiguration _) { using var socket = Zer0Mq.Go().BuildWithInProc("bus-interface"); socket.Respond <Request, Response>((r) => new Response()); var response = await socket.RequestAsync <Request, Response>(new Request()); System.Console.WriteLine(response.InsideResponse); }
private ISocket Build(SocketConfiguration configuration) { configuration.Serializer = _serializer; configuration.Logger = _logger; if (_isSilent) { _logger.SetSilent(); } return(new Socket(configuration)); }
internal static async Task SimplePubSub(SocketConfiguration configuration) { ISocket socket = ToSocket(configuration); socket.RegisterSubscriber <PubSubMessage>(msg => System.Console.WriteLine("msg received: " + msg.Message)); await socket.PublishAsync(new PubSubMessage { Message = "Published simply" }); Console.ReadLine(); socket.Dispose(); }
// socket came late, for now no refactoring of all tests desired private static ISocket ToSocket(SocketConfiguration configuration) { if (configuration is SocketConfiguration.Tcp tcp) { string port = tcp.Address().Split(":").Last(); return(Zer0Mq.Go().BuildWithTcp("localhost", port)); } else { return(Zer0Mq.Go().BuildWithInProc(configuration.Address().Split("//").Last())); } }
private static SocketConfiguration BuildConfig(string[] args, int index) { var version = args.FirstOrDefault(); var protocol = args.LastOrDefault(); SocketConfiguration configuration = SocketConfiguration.InprocConfig($"this-inproc-sir-{Guid.NewGuid()}"); if (protocol != null && protocol != version) { configuration = SocketConfiguration.TcpConfig($"555{index}"); } configuration.TimeOut = TimeSpan.FromSeconds(2); return(configuration); }
internal SubscriberHandler(SubscriberSocket subscriberSocket, SocketConfiguration configuration, NetMQPoller poller, CancellationToken token, Action <TMessage> syncCallback = null, Func <TMessage, Task> asyncCallback = null) { _token = token; _poller = poller; _socket = subscriberSocket; _configuration = configuration; _syncCallback = syncCallback; _asyncCallback = asyncCallback; }
internal static async Task AsyncServer(SocketConfiguration configuration) { using var socket = new RqRep(configuration); socket.RespondAsync <Request, Response>(async r => { await Task.Delay(100); return(new Response { InsideResponse = "waited asynchronously for 100ms" }); } ); await RequestAndWriteResultAsync(socket); }
internal static RoundBasedRegisterTestSetup CreateRoundBasedRegister(IEnumerable <string> synod, string localNodeUri) { var appConfig = new RendezvousServiceConfiguration { Synod = new SynodConfiguration { Members = synod, LocalNode = localNodeUri, HeartBeatInterval = TimeSpan.FromSeconds(5), IntercomEndpoint = $"inproc://{Guid.NewGuid()}", MissingHeartBeatsBeforeReconnect = 4 }, Lease = new LeaseConfiguration { ClockDrift = TimeSpan.FromMilliseconds(10), MessageRoundtrip = TimeSpan.FromMilliseconds(100), NodeResponseTimeout = TimeSpan.FromMilliseconds(1000), MaxLeaseTimeSpan = TimeSpan.FromSeconds(3) } }; var socketConfig = new SocketConfiguration { ReceivingHighWatermark = 1000, SendingHighWatermark = 1000, Linger = TimeSpan.Zero }; var logger = new Mock <ILogger>(); var performanceCounterManager = new Mock <IPerformanceCounterManager <KinoPerformanceCounters> >(); var synodConfigProvider = new SynodConfigurationProvider(appConfig.Synod); var intercomMessageHub = new IntercomMessageHub(new SocketFactory(socketConfig), synodConfigProvider, performanceCounterManager.Object, logger.Object); var ballotGenerator = new BallotGenerator(appConfig.Lease); var roundBasedRegister = new RoundBasedRegister(intercomMessageHub, ballotGenerator, synodConfigProvider, appConfig.Lease, logger.Object); logger.Verify(m => m.Error(It.IsAny <object>()), Times.Never); return(new RoundBasedRegisterTestSetup(ballotGenerator, synodConfigProvider.LocalNode, roundBasedRegister)); }
internal static async Task CancellationTokenOnRunningTask(SocketConfiguration configuration) { var socket = new RqRep(configuration); using var cts = new CancellationTokenSource(); var token = cts.Token; SetupResponder(socket, token: token); cts.Cancel(); // the first one will always come through, no matter what System.Console.WriteLine("try multiple requests"); foreach (var item in Enumerable.Range(0, 3)) { await RequestAndWriteResultAsync(socket); } }
private static Task Main(/*string[] args*/) { Console.WriteLine("SocketServerApp is running..."); var hostName = Dns.GetHostName(); var socketConfiguration = new SocketConfiguration(hostName, 3333); var tcpListener = socketConfiguration.CreateTcpListener(); tcpListener.Start(); while (true) { var handler = tcpListener.AcceptTcpClient(); var clientHandler = new TcpClientHandler(handler); clientHandler.StartAsync(); } }
internal static async Task PubSubWithCancellation(SocketConfiguration configuration) { ISocket socket = ToSocket(configuration); using var cts = new CancellationTokenSource(); var token = cts.Token; socket.RegisterSubscriber <PubSubMessage>(msg => System.Console.WriteLine("msg received: " + msg.Message), token); cts.Cancel(); System.Console.WriteLine("try multiple Publishes"); foreach (var item in Enumerable.Range(0, 3)) { await socket.PublishAsync(new PubSubMessage { Message = "Published with cancellation" }); } System.Console.WriteLine("press any key to exit"); Console.ReadLine(); socket.Dispose(); }
public void publisher_should_ignore_ReceiveTimeout_in_socket_configuration_and_must_not_disconnect_on_timeout() { using (var publisher = new Publisher()) using (var subscriber = new Subscriber()) { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { ReceiveTimeout = TimeSpan.FromMilliseconds(100) }; var disconnected = new ManualResetEventSlim(); publisher.ClientDisconnected += s => disconnected.Set(); publisher.Bind(endpoint, socketConfiguration); subscriber.Connect(endpoint); Assert.IsFalse(disconnected.Wait(TimeSpan.FromSeconds(1))); } }
public void ServiceQueueReader_should_obey_ReceiveTimeout_in_socket_configuration_and_disconnects_on_timeout() { using (var serviceQueue = new ServiceQueue()) using (var serviceQueueReader = new ServiceQueueReader()) { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { ReceiveTimeout = TimeSpan.FromMilliseconds(100) }; serviceQueue.Bind(endpoint); serviceQueueReader.Connect(endpoint, socketConfiguration); var disconnected = new ManualResetEventSlim(); serviceQueueReader.Disconnected += disconnected.Set; Assert.IsTrue(disconnected.Wait(TimeSpan.FromSeconds(1))); } }
public void Requester_Request_should_obey_ReceiveTimeout_in_socket_configuration_and_throw_IOException() { using (var responder = TestHelpers.CreateTestResponder(1000)) using (var requester = new Requester()) { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { ReceiveTimeout = TimeSpan.FromMilliseconds(100) }; responder.Bind(endpoint); requester.Connect(endpoint, socketConfiguration); var disconnected = new ManualResetEventSlim(); requester.Disconnected += disconnected.Set; Assert.Throws <IOException>(() => requester.Request(new TestMessage())); } }
internal static Task Contest(SocketConfiguration _) { using var socket = Zer0Mq.Go().BuildWithInProc("contestion"); socket.Respond <Request, Response>(rq => new Response { InsideResponse = "first-server" }); try { var socket2 = Zer0Mq.Go().BuildWithInProc("contestion"); socket2.Respond <Request, Response>(rq => new Response { InsideResponse = "second-server" }); } catch (ZeroMqXtSocketException socketException) { System.Console.WriteLine("expected exception was thrown: " + socketException.ToString()); return(Task.CompletedTask); } throw new InvalidOperationException("Socketexception (AdressAlready In Use) expected"); }
public void Clone() { var socketConfiguration = new SocketConfiguration { ConnectTimeout = TimeSpan.FromSeconds(1), ReceiveTimeout = TimeSpan.FromSeconds(2), SendTimeout = TimeSpan.FromSeconds(3), ReceiveBufferSize = 4, SendBufferSize = 5 }; var cloned = socketConfiguration.Clone(); Assert.AreNotSame(socketConfiguration, cloned); Assert.AreEqual(socketConfiguration.ConnectTimeout, cloned.ConnectTimeout); Assert.AreEqual(socketConfiguration.ReceiveTimeout, cloned.ReceiveTimeout); Assert.AreEqual(socketConfiguration.SendTimeout, cloned.SendTimeout); Assert.AreEqual(socketConfiguration.ReceiveBufferSize, cloned.ReceiveBufferSize); Assert.AreEqual(socketConfiguration.SendBufferSize, cloned.SendBufferSize); }
public void SendReceiveAndVerify_times_out_after_ConnectTimeout() { var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp); var socketConfiguration = new SocketConfiguration { ConnectTimeout = TimeSpan.FromSeconds(2) }; var server = new TcpListener(IPAddress.Loopback, endpoint.Port); server.Start(); try { server.AcceptTcpClientAsync(); var nodeGreetingVerifier = new NodeGreetingMessageVerifier(NodeType.Publisher, NodeType.Subscriber); var socket = new SocketFactory().CreateAndConnectAsync(endpoint, NodeType.Subscriber, socketConfiguration); var sw = Stopwatch.StartNew(); var task = Task.Factory.StartNew(() => { nodeGreetingVerifier.SendReceiveAndVerify(socket, socketConfiguration.ConnectTimeout); }); var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { task.Wait(cancellationToken.Token); } catch (AggregateException ex) { Assert.AreEqual(typeof(TimeoutException), ex.InnerExceptions.Single().GetType()); } Assert.Greater(sw.Elapsed, socketConfiguration.ConnectTimeout); } finally { server.Stop(); } }
internal static RoundBasedRegisterTestSetup CreateRoundBasedRegister(IEnumerable <string> synod, string localNodeUri) { var appConfig = new RendezvousServiceConfiguration { Synod = new SynodConfiguration { Members = synod, LocalNode = localNodeUri }, Lease = new LeaseConfiguration { ClockDrift = TimeSpan.FromMilliseconds(10), MessageRoundtrip = TimeSpan.FromMilliseconds(100), NodeResponseTimeout = TimeSpan.FromMilliseconds(1000), MaxLeaseTimeSpan = TimeSpan.FromSeconds(3) } }; var socketConfig = new SocketConfiguration { ReceivingHighWatermark = 1000, SendingHighWatermark = 1000, Linger = TimeSpan.Zero }; var synodConfig = new global::kino.Consensus.Configuration.SynodConfiguration(new SynodConfigurationProvider(appConfig.Synod)); var logger = new Mock <ILogger>(); var performanceCounterManager = new Mock <IPerformanceCounterManager <KinoPerformanceCounters> >(); var intercomMessageHub = new IntercomMessageHub(new SocketFactory(socketConfig), synodConfig, performanceCounterManager.Object, logger.Object); var ballotGenerator = new BallotGenerator(appConfig.Lease); var roundBasedRegister = new RoundBasedRegister(intercomMessageHub, ballotGenerator, synodConfig, appConfig.Lease, logger.Object); return(new RoundBasedRegisterTestSetup(ballotGenerator, synodConfig.LocalNode, roundBasedRegister, appConfig.Lease.MaxLeaseTimeSpan)); }
private void BuildContainer() { var socketConf = new SocketConfiguration { //Host = "192.168.43.166", Host = "80.68.231.116", //Host = "127.0.0.1", Port = 2138 }; var loggerConfig = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Console(); var builder = new ContainerBuilder() .RegisterSerilog(loggerConfig) .AddSocketClientConnection(socketConf) .AddSocketClientEventBus(); builder.RegisterType <RoverControlCommandHandler>().InstancePerDependency(); _container = builder.Build(); }
public EasyClient(ILogger <EasyClient> logger = null, IConfiguration config = null) { _logger = logger; _config = config; try { if (config != null) { EasyClientConfiguration = _config.GetSection("EasyClient").Get <EasyClientConfiguration>(); SocketConfiguration = _config.GetSection("EasyClient").GetSection("EasySocket").Get <SocketConfiguration>(); } else { EasyClientConfiguration = new EasyClientConfiguration(); SocketConfiguration = new SocketConfiguration(); } } catch (Exception exception) { throw new Exception("Failed to initialize easy client...", exception); } }