/// <summary> /// Create the DEALER socket and connect it to QUEUE backend. /// Set the identity. /// Send the initial READY message. /// </summary> private static DealerSocket GetWorkerSocket(bool verbose, int id) { var worker = new DealerSocket { Options = { Identity = Encoding.UTF8.GetBytes("Worker_" + id) } }; worker.ReceiveReady += OnWorkerReceiveReady; worker.Connect(Commons.QueueBackend); if (verbose) { Console.WriteLine("[WORKER] {0} sending 'READY'.", Encoding.UTF8.GetString(worker.Options.Identity)); } // send READY worker.SendFrame(Commons.PPPReady); return(worker); }
public void Start() { using (_dealer = new DealerSocket()) { _dealer.Bind(_dealerEndpoint); using (_router = new RouterSocket(_routerEndpoint)) { while (!_cancel.IsCancellationRequested) { var msg = _router.ReceiveMultipartMessage(); _dealer.SendFrame(msg[1].Buffer); Handled++; } } } }
public void BindToLocal() { var validAliasesForLocalHost = new[] { "127.0.0.1", "localhost", Dns.GetHostName() }; foreach (var alias in validAliasesForLocalHost) { using (var localDealer = new DealerSocket()) using (var connectingDealer = new DealerSocket()) { var port = localDealer.BindRandomPort("tcp://*"); connectingDealer.Connect($"tcp://{alias}:{port}"); localDealer.SendFrame("test"); Assert.AreEqual("test", connectingDealer.ReceiveFrameString()); Console.WriteLine(alias + " connected "); } } }
public void TwoMessagesFromRouterToDealer() { using (var server = new RouterSocket()) using (var client = new DealerSocket()) using (var poller = new NetMQPoller { client }) { var port = server.BindRandomPort("tcp://*"); client.Connect("tcp://127.0.0.1:" + port); var cnt = 0; client.ReceiveReady += (sender, e) => { e.Socket.ReceiveMultipartStrings(); cnt++; if (cnt == 2) { poller.Stop(); } }; byte[] clientId = Encoding.Unicode.GetBytes("ClientId"); client.Options.Identity = clientId; const string request = "GET /\r\n"; const string response = "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello, World!"; client.SendFrame(request); byte[] serverId = server.ReceiveFrameBytes(); Assert.AreEqual(request, server.ReceiveFrameString()); // two messages in a row, not frames server.SendMoreFrame(serverId).SendFrame(response); server.SendMoreFrame(serverId).SendFrame(response); poller.Run(); } }
static void Main(string[] args) { Console.WriteLine("====== WORKER ======"); using (var pull = new PullSocket()) using (var sink = new DealerSocket()) { pull.Connect("tcp://127.0.0.1:8888"); sink.Connect("tcp://127.0.0.1:7777"); while (true) { var workload = pull.ReceiveFrameString(); Thread.Sleep(int.Parse(workload)); Console.WriteLine("Sending to Sink"); sink.SendFrame(string.Empty); } } }
public async Task Start() { _server.Bind(_localConnectionString); _poller.Add(_server); _poller.RunAsync(); foreach (var connStr in _peerConnectionStrings) { DealerSocket peer = new DealerSocket(); peer.Options.Identity = _nodeId.ToByteArray(); peer.ReceiveReady += Peer_ReceiveReady; peer.Connect(connStr); _poller.Add(peer); peer.SendFrame(ConvertOp(MessageOp.Ping)); } _houseKeeper = new NetMQTimer(TimeSpan.FromSeconds(30)); _houseKeeper.Elapsed += HouseKeeper_Elapsed; _poller.Add(_houseKeeper); _houseKeeper.Enable = true; }
public void Execute() { using (var placaValidationBackend = new DealerSocket(DELAER)) using (var placaValidationSubcriptionSocket = new SubscriberSocket(SUBSCRIBER)) { placaValidationSubcriptionSocket.Subscribe("validation"); CreateState(); Console.WriteLine($"Placa on"); Console.WriteLine($"Delaer running on: {DELAER}"); Console.WriteLine($"Listening to: {SUBSCRIBER}"); while (true) { try { var topic_placa = placaValidationSubcriptionSocket.ReceiveFrameString(); var request_to_validate_placa = placaValidationSubcriptionSocket.ReceiveFrameString(); Console.WriteLine($"Log placa para validacao recebido: {request_to_validate_placa}"); var envelope = Newtonsoft.Json.JsonConvert.DeserializeObject<Envelope>(request_to_validate_placa); envelope.ValidationMessages = GetValidationMessages(envelope.Message); request_to_validate_placa = Newtonsoft.Json.JsonConvert.SerializeObject(envelope); Console.WriteLine("Sending Placa: " + request_to_validate_placa); placaValidationBackend.SendFrame(request_to_validate_placa); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
public void NoBlock() { const int count = 1000; NetMQConfig.Linger = TimeSpan.FromSeconds(0.5); using (var client = new DealerSocket(">tcp://localhost:5557")) { // Sending a lot of messages client.Options.SendHighWatermark = count; for (int i = 0; i < count; i++) { client.SendFrame("Hello"); } } Stopwatch stopwatch = Stopwatch.StartNew(); NetMQConfig.Cleanup(false); stopwatch.Stop(); Assert.Less(stopwatch.ElapsedMilliseconds, 500); }
public void Mandatory() { using (var router = new RouterSocket()) { router.Options.RouterMandatory = true; router.Bind("tcp://127.0.0.1:5555"); using (var dealer = new DealerSocket()) { dealer.Options.Identity = Encoding.ASCII.GetBytes("1"); dealer.Connect("tcp://127.0.0.1:5555"); dealer.SendFrame("Hello"); Assert.AreEqual("1", router.ReceiveFrameString()); Assert.AreEqual("Hello", router.ReceiveFrameString()); } Thread.Sleep(100); Assert.Throws <HostUnreachableException>(() => router.SendMoreFrame("1").SendFrame("Hello")); } }
public void Execute() { using (var validationBackendSocket = new DealerSocket(DELAER)) using (var validationfrontEnd = new SubscriberSocket(VALIDATION_FRONTEND_ENDPOINT)) { validationfrontEnd.Subscribe("validation"); Console.WriteLine($"Validation ONNNNNNNNNNNNNNNNNN"); Console.WriteLine($"Dealer on: {DELAER}"); Console.WriteLine($"Listening to: {VALIDATION_FRONTEND_ENDPOINT}"); while (true) { try { var topic = validationfrontEnd.ReceiveFrameString(); var message_to_validate = validationfrontEnd.ReceiveFrameString(); var envelope = Newtonsoft.Json.JsonConvert.DeserializeObject <Envelope>(message_to_validate); Console.WriteLine($"Log validacao received: {envelope.Identity}"); envelope.ValidationMessages = GetValidationMessages(envelope.Message); message_to_validate = Newtonsoft.Json.JsonConvert.SerializeObject(envelope); Console.WriteLine("Sending Validation: " + envelope.Identity); validationBackendSocket.SendFrame(message_to_validate); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
private IStateReply GetStateOfTheWorld() { using (var dealer = new DealerSocket()) { var request = new StateRequest() { Subject = _configuration.Subject, }; var requestBytes = _eventSerializer.Serializer.Serialize(request); dealer.Connect(_configuration.StateOfTheWorldEndpoint); dealer.SendFrame(requestBytes); var hasResponse = dealer.TryReceiveFrameBytes(_configuration.StateCatchupTimeout, out var responseBytes); if (!hasResponse) { throw new Exception("unable to reach broker"); } return(_eventSerializer.Serializer.Deserialize <StateReply>(responseBytes)); } }
public void AddSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool router1Arrived = false; bool router2Arrived = false; bool router3Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived = true; router1.SkipFrame(); router1.SkipFrame(); poller.Remove(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived = true; router2.SkipFrame(); router2.SkipFrame(); poller.Add(router3); signal2.Set(); }; router3.ReceiveReady += (s, e) => { router3Arrived = true; router3.SkipFrame(); router3.SkipFrame(); signal3.Set(); }; poller.RunAsync(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); Assert.IsTrue(signal3.WaitOne(300)); poller.Stop(); Assert.IsTrue(router1Arrived); Assert.IsTrue(router2Arrived); Assert.IsTrue(router3Arrived); } }
public void SendTopicData(TopicData td) { byte[] buffer = td.ToByteArray(); socket.SendFrame(buffer); }
public XplaneConnectionManager(IEventBroker broker, IAppConfig config, IFsdManger fsdManager) : base(broker) { DealerSocket visualDealerSocket = null; mVisualDealerSockets = null; mConfig = config; mFsdManager = fsdManager; if (mConfig.VisualClientIPs.Count > 0) { foreach (string mIP in mConfig.VisualClientIPs) { visualDealerSocket = new DealerSocket(); visualDealerSocket.Options.Identity = Encoding.UTF8.GetBytes("CLIENT"); visualDealerSocket.Options.TcpKeepalive = true; try { visualDealerSocket.Connect("tcp://" + mIP + ":" + mConfig.TcpPort); if (mVisualDealerSockets == null) { mVisualDealerSockets = new List <DealerSocket>(); } mVisualDealerSockets.Add(visualDealerSocket); } catch (AddressAlreadyInUseException) { NotificationPosted?.Invoke(this, new NotificationPostedEventArgs(NotificationType.Error, "Plugin port already in use. Please choose a different TCP port.")); } } } if (!string.IsNullOrEmpty(mConfig.SimClientIP)) { mSimulatorIP = mConfig.SimClientIP; } mMessageQueue = new NetMQQueue <string>(); mDealerSocket = new DealerSocket(); mDealerSocket.Options.TcpKeepalive = true; mDealerSocket.Options.Identity = Encoding.UTF8.GetBytes("CLIENT"); mDealerSocket.ReceiveReady += DealerSocket_ReceiveReady; try { mDealerSocket.Connect("tcp://" + mSimulatorIP + ":" + mConfig.TcpPort); } catch (AddressAlreadyInUseException) { NotificationPosted?.Invoke(this, new NotificationPostedEventArgs(NotificationType.Error, "Plugin port already in use. Please choose a different TCP port.")); } mPoller = new NetMQPoller { mDealerSocket, mMessageQueue }; if (!mPoller.IsRunning) { mPoller.RunAsync(); } mMessageQueue.ReceiveReady += (s, e) => { if (mMessageQueue.TryDequeue(out string msg, TimeSpan.FromMilliseconds(100))) { if (mDealerSocket != null) { mDealerSocket.SendFrame(msg); } if (mVisualDealerSockets != null && mVisualDealerSockets.Count > 0) { foreach (DealerSocket socket in mVisualDealerSockets) { socket.SendFrame(msg); } } } }; mXplaneConnector = new XPlaneConnector.XPlaneConnector(mSimulatorIP); mUserAircraftData = new UserAircraftData(); mRadioStackState = new UserAircraftRadioStack(); mGetXplaneDataTimer = new Timer { Interval = 10 }; mGetXplaneDataTimer.Tick += GetXplaneDataTimer_Tick; mGetXplaneDataTimer.Start(); mConnectionTimer = new Timer { Interval = 50 }; mConnectionTimer.Tick += ConnectionTimer_Tick; mConnectionTimer.Start(); mRetryConnectionTimer = new Timer { Interval = 1000 }; mRetryConnectionTimer.Tick += RetryConnectionTimer_Tick; mRetryConnectionTimer.Start(); mWhosOnlineListRefresh = new Timer { Interval = 5000 }; mWhosOnlineListRefresh.Tick += WhosOnlineListRefresh_Tick; SetupSubscribers(); if (!Directory.Exists(Path.Combine(mConfig.AppPath, "PluginLogs"))) { Directory.CreateDirectory(Path.Combine(mConfig.AppPath, "PluginLogs")); } var directory = new DirectoryInfo(Path.Combine(mConfig.AppPath, "PluginLogs")); var query = directory.GetFiles("*", SearchOption.AllDirectories); foreach (var file in query.OrderByDescending(file => file.CreationTime).Skip(10)) { file.Delete(); } mRawDataStream = new StreamWriter(Path.Combine(mConfig.AppPath, string.Format($"PluginLogs/PluginLog-{DateTime.UtcNow:yyyyMMddHHmmss}.log")), false); }
public void AddTwoSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var router4 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var dealer4 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); int port4 = router4.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); dealer4.Connect("tcp://127.0.0.1:" + port4); int router1Arrived = 0; int router2Arrived = 0; bool router3Arrived = false; bool router4Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); var signal4 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived++; router1.SkipFrame(); // identity router1.SkipFrame(); // message poller.Remove(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived++; router2.SkipFrame(); // identity router2.SkipFrame(); // message if (router2Arrived == 1) { poller.Add(router3); poller.Add(router4); signal2.Set(); } }; router3.ReceiveReady += (s, e) => { router3.SkipFrame(); // identity router3.SkipFrame(); // message router3Arrived = true; signal3.Set(); }; router4.ReceiveReady += (s, e) => { router4.SkipFrame(); // identity router4.SkipFrame(); // message router4Arrived = true; signal4.Set(); }; poller.RunAsync(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); dealer4.SendFrame("4"); dealer2.SendFrame("2"); dealer1.SendFrame("1"); Assert.IsTrue(signal3.WaitOne(300)); Assert.IsTrue(signal4.WaitOne(300)); poller.Stop(); router1.SkipFrame(); bool more; Assert.AreEqual("1", router1.ReceiveFrameString(out more)); Assert.IsFalse(more); Assert.AreEqual(1, router1Arrived); Assert.AreEqual(2, router2Arrived); Assert.IsTrue(router3Arrived); Assert.IsTrue(router4Arrived); } }
public void RemoveSocket() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2, router3 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool first = true; router1.ReceiveReady += (s, e) => { if (!first) { Assert.Fail("This should not happen because we cancelled the socket"); } first = false; // identity e.Socket.SkipFrame(); bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); // cancelling the socket poller.Remove(e.Socket); // remove self }; router2.ReceiveReady += (s, e) => { // identity byte[] identity = e.Socket.ReceiveFrameBytes(); // message e.Socket.SkipFrame(); e.Socket.SendMoreFrame(identity); e.Socket.SendFrame("2"); }; router3.ReceiveReady += (s, e) => { // identity byte[] identity = e.Socket.ReceiveFrameBytes(); // message e.Socket.SkipFrame(); e.Socket.SendMoreFrame(identity).SendFrame("3"); }; Task pollerTask = Task.Factory.StartNew(poller.Run); // Send three messages. Only the first will be processed, as then handler removes // the socket from the poller. dealer1.SendFrame("Hello"); dealer1.SendFrame("Hello2"); dealer1.SendFrame("Hello3"); // making sure the socket defined before the one cancelled still works dealer2.SendFrame("1"); Assert.AreEqual("2", dealer2.ReceiveFrameString()); // making sure the socket defined after the one cancelled still works dealer3.SendFrame("1"); Assert.AreEqual("3", dealer3.ReceiveFrameString()); poller.Stop(); Assert.IsTrue(pollerTask.IsCompleted); } }
/// <summary> /// Create the DEALER socket and connect it to QUEUE backend. /// Set the identity. /// Send the initial READY message. /// </summary> private static DealerSocket GetWorkerSocket(bool verbose, int id) { var worker = new DealerSocket { Options = { Identity = Encoding.UTF8.GetBytes("Worker_" + id) } }; worker.Connect(Commons.QueueBackend); if (verbose) Console.WriteLine("[WORKER] {0} sending 'READY'.", Encoding.UTF8.GetString(worker.Options.Identity)); // send READY worker.SendFrame(Commons.PPPReady); return worker; }
public void Unbind(string protocol) { using (var server = new DealerSocket()) { string address1, address2; // just making sure can bind on both addresses using (var client1 = new DealerSocket()) using (var client2 = new DealerSocket()) { if (protocol == "tcp") { var port1 = server.BindRandomPort("tcp://localhost"); var port2 = server.BindRandomPort("tcp://localhost"); address1 = "tcp://localhost:" + port1; address2 = "tcp://localhost:" + port2; client1.Connect(address1); client2.Connect(address2); } else { Debug.Assert(protocol == "inproc"); address1 = "inproc://localhost1"; address2 = "inproc://localhost2"; server.Bind(address1); server.Bind(address2); client1.Connect(address1); client2.Connect(address2); } Thread.Sleep(100); // we should be connected to both server client1.SendFrame("1"); client2.SendFrame("2"); // the server receive from both server.SkipFrame(); server.SkipFrame(); } // unbind second address server.Unbind(address2); Thread.Sleep(100); using (var client1 = new DealerSocket()) using (var client2 = new DealerSocket()) { client1.Options.DelayAttachOnConnect = true; client1.Connect(address1); client2.Options.DelayAttachOnConnect = true; if (protocol == "tcp") { client2.Connect(address2); client1.SendFrame("1"); server.SkipFrame(); Assert.IsFalse(client2.TrySendFrame(TimeSpan.FromSeconds(2), "2")); } else { Assert.Throws <EndpointNotFoundException>(() => { client2.Connect(address2); }); } } } }
public void AddSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new Poller(router1, router2) { PollTimeout = TestPollTimeoutMillis }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool router1Arrived = false; bool router2Arrived = false; bool router3Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived = true; router1.SkipFrame(); router1.SkipFrame(); poller.RemoveSocket(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived = true; router2.SkipFrame(); router2.SkipFrame(); poller.AddSocket(router3); signal2.Set(); }; router3.ReceiveReady += (s, e) => { router3Arrived = true; router3.SkipFrame(); router3.SkipFrame(); signal3.Set(); }; poller.PollTillCancelledNonBlocking(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); Assert.IsTrue(signal3.WaitOne(300)); poller.CancelAndJoin(); Assert.IsTrue(router1Arrived); Assert.IsTrue(router2Arrived); Assert.IsTrue(router3Arrived); } }