/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected (Linger is set to 1) /// The Client connects to broker using a DEALER socket /// </summary> private void Connect() { if (!ReferenceEquals(m_client, null)) { m_poller.Remove(m_client); m_client.Dispose(); } m_client = new DealerSocket(); // sets a low linger to avoid port exhaustion, messages can be lost since it'll be sent again m_client.Options.Linger = m_lingerTime; if (m_identity != null) { m_client.Options.Identity = m_identity; } // set timeout timer to reconnect if no message is received during timeout m_timer.EnableAndReset(); // attach the event handler for incoming messages m_client.ReceiveReady += OnProcessReceiveReady; m_poller.Add(m_client); // TODO Define HighWaterMark!? m_client.Connect(m_brokerAddress); m_connected = true; Log($"[CLIENT] connecting to broker at {m_brokerAddress}"); }
private void OnSubscriberMessage(object sender, NetMQSocketEventArgs e) { // we just forward the message to the actor var message = _subscriber.ReceiveMultipartMessage(); Debug.WriteLine(message); var topic = message[0].ConvertToString(); if (topic == WelcomeMessage) { SubscriberAddress = e.Socket.Options.LastEndpoint; Debug.WriteLine($"Subsciber Address: {SubscriberAddress}"); _welcomeMessageHandler?.Invoke(); } else if (topic == HeartbeatMessage) { // we got a heartbeat, lets postponed the timer _timeoutTimer.EnableAndReset(); } else { _shim.SendMultipartMessage(message); } }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected (Linger is set to 1) /// The Client connects to broker using a DEALER socket /// </summary> private void Connect() { if (!ReferenceEquals(m_client, null)) { DisposeClient(); } m_client = new DealerSocket(); // sets a low linger to avoid port exhaustion, messages can be lost since it'll be sent again m_client.Options.Linger = m_lingerTime; if (m_identity != null) { m_client.Options.Identity = m_identity; } // set timeout timer to reconnect if no message is received during timeout m_lastReceivedRequest = DateTime.UtcNow; m_timer.EnableAndReset(); // attach the event handler for incoming messages m_client.ReceiveReady += OnReceiveReady; m_client.SendReady += OnSendReady; m_poller.Add(m_client); RotateBroker(); m_client.Connect(Address); m_connected = true; Log($"[CLIENT]: {m_client.Options.Identity} connecting to broker at {Address}"); }
/// <summary> /// On date received handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnReceive(object sender, NetMQSocketEventArgs e) { //Go trough all received items while (e.Socket.TryReceiveFrameString(out string topic)) { if (topic == Topic.HistoryMessage || topic == Topic.BackfillingMessage) { //Get subscription string subscription = e.Socket.ReceiveFrameString(); //Check if we know this data type ProcessData(e.Socket.ReceiveFrameBytes()); //Timer reset (if we are expecting data) if (LastDataReceivedUtc.Date < _endDateTime.AddDays(-1)) { _timeoutTimer.EnableAndReset(); } else { _timeoutTimer.Enable = false; } } else //Unknown topic { } } }
/// <summary> /// On data received handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnReceive(object sender, NetMQSocketEventArgs e) { //Go trough all received items while (e.Socket.TryReceiveFrameString(out string topic)) { if (topic == Topic.WelcomeMessage) { //Welcome message _log.Debug("Received welcome message"); } else if (topic == Topic.HeartBeatMessage) { //Heartbeat (reset timeout) _timeoutTimer.EnableAndReset(); } else if (topic == Topic.DataMessage) { //Get subscription string subscription = e.Socket.ReceiveFrameString(); //Process data ProcessData(e.Socket.ReceiveFrameBytes()); } else //Unknown topic { //TODO: keep reading until we get the next topic, so we can skip this message from the feed } } }
/// <summary> /// Connect or re-connect to the broker. /// </summary> private void Connect() { // if the socket exists dispose it and re-create one if (!ReferenceEquals(m_worker, null)) { DisposeWorker(); } m_worker = new DealerSocket(); // set identity if provided if (m_identity != null && m_identity.Length > 0) { m_worker.Options.Identity = m_identity; } m_timer.Interval = (int)HeartbeatDelay.TotalMilliseconds; m_timer.EnableAndReset(); // hook up the received message processing method before the socket is connected m_worker.ReceiveReady += ProcessReceiveReady; m_poller.Add(m_worker); m_worker.Connect(m_brokerAddress); Log($"[WORKER] connected to broker at {m_brokerAddress}"); // send READY to broker since worker is connected m_pollerQueue.Enqueue(() => Send(MDPCommand.Ready, m_serviceName, null)); // reset liveliness to active broker m_liveliness = _heartbeat_liveliness; // set point in time for next heatbeat m_heartbeatAt = DateTime.UtcNow + HeartbeatDelay; }
/// <summary> /// Called when data was received /// </summary> /// <param name="data">The data.</param> private void OnData(string data) { try { //Reset timer _timeoutTimer.EnableAndReset(); //Data capture DataCapture?.Invoke(data); //Convert and use if (TryConvert(data, out DataPoint[] datapoint))
public void ResetTimer() { using (NetMQContext context = NetMQContext.Create()) { const int timerIntervalMillis = 50; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis / 2)); int count = 0; timer1.Elapsed += (a, s) => { count++; }; timer2.Elapsed += (sender, args) => { timer1.EnableAndReset(); timer2.Enable = false; }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep((int)(timerIntervalMillis * 1.1)); // it shouldn't have run Assert.AreEqual(0, count); Thread.Sleep((int)(timerIntervalMillis * 0.5)); // it should have run once Assert.AreEqual(1, count); poller.CancelAndJoin(); } } }
private void OnShimMessage(object sender, NetMQSocketEventArgs e) { string command; while (e.Socket.TryReceiveFrameString(out command)) { if (command == PublishMessageCommand) { // just forward the message to the publisher NetMQMessage message = e.Socket.ReceiveMultipartMessage(); _publisherSocket.SendMultipartMessage(message); _receiveTimeoutTimer?.EnableAndReset(); } else if (command == NetMQActor.EndShimMessage) { // we got dispose command, we just stop the poller _poller.Stop(); } } }
private void Connect() { _reconnectTimer.Enable = false; _timeoutTimer.Enable = false; var sockets = new List <SubscriberSocket>(); var poller = new NetMQPoller(); SubscriberSocket connectedSocket = null; // event handler to handle message from socket void HandleMessage(object sender, NetMQSocketEventArgs args) { connectedSocket = (SubscriberSocket)args.Socket; poller.Stop(); } var timeoutTimer = new NetMQTimer(_heartbeatTimeOut); // just cancel the poller without seting the connected socket timeoutTimer.Elapsed += (sender, args) => poller.Stop(); poller.Add(timeoutTimer); foreach (var address in _addresses) { var socket = new SubscriberSocket(); sockets.Add(socket); socket.ReceiveReady += HandleMessage; poller.Add(socket); // Subscribe to welcome message socket.Subscribe(WelcomeMessage); socket.Connect(address); } poller.Run(); // if we a connected socket the connection attempt succeed if (connectedSocket != null) { // remove the connected socket form the list sockets.Remove(connectedSocket); // close all exsiting connections foreach (var socket in sockets) { // to close them immediatly we set the linger to zero socket.Options.Linger = TimeSpan.Zero; socket.Dispose(); } // set the socket _subscriber = connectedSocket; // drop the welcome message _subscriber.SkipMultipartMessage(); // subscribe to heartbeat _subscriber.Subscribe(HeartbeatMessage); // subscribe to all subscriptions foreach (var subscription in _subscriptions) { _subscriber.Subscribe(subscription); } _subscriber.ReceiveReady -= HandleMessage; _subscriber.ReceiveReady += OnSubscriberMessage; _actor.ReceiveReady += OnActorMessage; _poller.Add(_actor); _poller.Add(_subscriber); _timeoutTimer.EnableAndReset(); } else { // close all exsiting connections foreach (var socket in sockets) { // to close them immediatly we set the linger to zero socket.Options.Linger = TimeSpan.Zero; socket.Dispose(); } _reconnectTimer.EnableAndReset(); } }
public void ResetTimer() { const int timerIntervalMillis = 50; var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis / 2)); int count = 0; timer1.Elapsed += (a, s) => { count++; }; timer2.Elapsed += (sender, args) => { timer1.EnableAndReset(); timer2.Enable = false; }; using (var poller = new Poller(timer1, timer2) { PollTimeout = TestPollTimeoutMillis }) { poller.PollTillCancelledNonBlocking(); Thread.Sleep((int)(timerIntervalMillis * 1.1)); // it shouldn't have run Assert.AreEqual(0, count); Thread.Sleep((int)(timerIntervalMillis * 0.5)); // it should have run once Assert.AreEqual(1, count); poller.CancelAndJoin(); } }