static void Main(string[] args) { using (WSRouter router = new WSRouter()) using (WSPublisher publisher = new WSPublisher()) { router.Bind("ws://localhost:80"); publisher.Bind("ws://localhost:81"); router.ReceiveReady += (sender, eventArgs) => { byte[] identity = router.ReceiveFrameBytes(); string message = router.ReceiveFrameString(); router.SendMoreFrame(identity); router.SendFrame("OK"); publisher.SendMoreFrame("chat"); publisher.SendFrame(message); }; NetMQPoller poller = new NetMQPoller(); poller.Add(router); // we must add the publisher to the poller although we are not registering to any event. // The internal stream socket handle connections and subscriptions and use the events internally poller.Add(publisher); poller.Run(); } }
public static void Run() { using (var publisherSocket = new XPublisherSocket()) { publisherSocket.SetWelcomeMessage("WM"); publisherSocket.Bind("tcp://*:6669"); // we just drop subscriptions publisherSocket.ReceiveReady += (sender, eventArgs) => publisherSocket.SkipMultipartMessage(); var poller = new NetMQPoller { publisherSocket }; // send a message every second var sendMessageTimer = new NetMQTimer(1000); poller.Add(sendMessageTimer); sendMessageTimer.Elapsed += (sender, eventArgs) => publisherSocket.SendMoreFrame("A").SendFrame(new Random().Next().ToString()); // send heartbeat every two seconds var heartbeatTimer = new NetMQTimer(2000); poller.Add(heartbeatTimer); heartbeatTimer.Elapsed += (sender, eventArgs) => publisherSocket.SendFrame("HB"); poller.Stop(); } }
private void Run(PairSocket shim) { m_shim = shim; shim.ReceiveReady += OnShimMessage; m_timeoutTimer = new NetMQTimer(TimeOut); m_timeoutTimer.Elapsed += OnTimeoutTimer; m_reconnectTimer = new NetMQTimer(ReconnectTimer); m_reconnectTimer.Elapsed += OnReconnectTimer; m_poller = new NetMQPoller { shim }; m_poller.Add(m_timeoutTimer); m_poller.Add(m_reconnectTimer); shim.SignalOK(); Connect(); m_poller.Run(); if (m_subscriber != null) { m_subscriber.Dispose(); } }
public void SendWrongMDPVersionFromBrokerNoLoggingShouldThrowApplicationException() { const string hostAddress = "tcp://localhost:5555"; // setup the counter socket for communication using (var broker = new RouterSocket()) using (var poller = new NetMQPoller()) using (var session = new MDPClientAsync(hostAddress)) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors broker.ReceiveReady += (s, e) => { // return empty reply var msg = e.Socket.ReceiveMultipartMessage(); // we expect to receive a 4 Frame message // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"] if (msg.FrameCount != 5) { Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount); } // REQUEST socket will strip the his address + empty frame // ROUTER has to add the address prelude in order to identify the correct socket(!) // [REQ ADR][EMPTY]["MDPC00"]["echo"]["REQUEST"] var clientAddress = msg.Pop(); msg.Pop(); // forget empty frame msg.Pop(); // drop the MDP Version Frame msg.Push("MDPC00"); // insert wrong MDP version msg.Push(NetMQFrame.Empty); msg.Push(clientAddress); // reinsert the client's address e.Socket.SendMultipartMessage(msg); }; int timeOutInMillis = 10000; var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong! timer.Elapsed += (s, e) => { Assert.Fail($"Waited {timeOutInMillis} and had no response from broker"); poller.Stop(); }; poller.Add(broker); poller.Add(timer); session.ReplyReady += (s, e) => { Assert.True(e.HasError()); Assert.That(e.Exception.Message, Is.StringContaining("MDP Version mismatch")); poller.Stop(); // To unlock the Task.Wait() }; var task = Task.Factory.StartNew(() => poller.Run()); var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") }); session.Send("echo", requestMessage); task.Wait(); } }
public void Run(PairSocket shim) { shim.SignalOK(); shim.ReceiveReady += OnShimReady; m_messagesPipe = new PairSocket(); m_messagesPipe.Connect(string.Format("inproc://wsrouter-{0}", m_id)); m_messagesPipe.ReceiveReady += OnMessagePipeReady; m_stream = new StreamSocket(); m_stream.ReceiveReady += OnStreamReady; m_poller = new NetMQPoller(); m_poller.Add(m_messagesPipe); m_poller.Add(shim); m_poller.Add(m_stream); m_messagesPipe.SignalOK(); m_poller.Run(); m_messagesPipe.Dispose(); m_stream.Dispose(); }
private void StartStationNetMQ() { try { _subscriber = new SubscriberSocket(); _subscriber.ReceiveReady += _subscriber_ReceiveReady; //_fileSubscriber = new SubscriberSocket(); _requester = new RequestSocket(); _poller = new NetMQPoller(); IsLocalClient = CheckIsLocalIP(this.Options.ServerAddress); _subscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgPubPort)); _subscriber.SubscribeToAnyTopic(); _requester.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgResPort)); //_fileSubscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.FilePubPort)); //_fileSubscriber.SubscribeToAnyTopic(); logger.InfoFormat("peripheral client netmq info: IP-{0},msg pub port:{1},msg res port:{2}", this.Options.ServerAddress, this.Options.MsgPubPort, this.Options.MsgResPort); // HockSocketEvents(true); //_poller.Add(_fileSubscriber); _poller.Add(_subscriber); _poller.Add(_requester); _poller.RunAsync(); Console.WriteLine("[Progress]:[4] Sub Listening"); // this.OnConnected(); } catch (Exception ex) { } }
public void SendEmptyReplyFromBrokerWithLoggingShouldThrowApplicationException() { const string hostAddress = "tcp://localhost:5555"; var loggingMessages = new List <string>(); // setup the counter socket for communication using (var broker = new RouterSocket()) using (var poller = new NetMQPoller()) using (var session = new MDPClientAsync(hostAddress)) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors broker.ReceiveReady += (s, e) => { // return empty reply var msg = e.Socket.ReceiveMultipartMessage(); // we expect to receive a 4 Frame message // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId] if (msg.FrameCount != 6) { Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount); } // REQUEST socket will strip the his address + empty frame // ROUTER has to add the address prelude in order to identify the correct socket(!) // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId] e.Socket.SendMultipartMessage(msg); }; session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info); session.ReplyReady += (s, e) => { Assert.That(loggingMessages.Count, Is.EqualTo(3)); Assert.That(loggingMessages[0], Is.EqualTo("[CLIENT] connecting to broker at tcp://localhost:5555")); Assert.That(loggingMessages[1].Contains("[CLIENT INFO] sending"), Is.True); Assert.That(loggingMessages[2].Contains("[CLIENT INFO] received"), Is.True); poller.Stop(); // To unlock the Task.Wait() }; poller.Add(broker); var task = Task.Factory.StartNew(() => poller.Run()); // well formed message var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") }); // correct call session.Send("echo", requestMessage); int timeOutInMillis = 10000; var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong! timer.Elapsed += (s, e) => { Assert.Fail($"Waited {timeOutInMillis} and had no response from broker"); poller.Stop(); }; poller.Add(timer); task.Wait(); } }
public LRUBroker(string frontConnectionString, string backendConnectionString) { _frontend = new RouterSocket(frontConnectionString); _backend = new RouterSocket(backendConnectionString); _frontend.ReceiveReady += FrontendReceiveReady; _backend.ReceiveReady += BackendReceiveReady; _poller.Add(_frontend); _poller.Add(_backend); }
public LRUBroker(string frontConnectionString, string backendConnectionString) { _frontend = new RouterSocket(frontConnectionString); _backend = new RouterSocket(); BackendPort = _backend.BindRandomPort(backendConnectionString.TrimStart(new char[] { '@' })); _frontend.ReceiveReady += FrontendReceiveReady; _backend.ReceiveReady += BackendReceiveReady; _poller.Add(_frontend); _poller.Add(_backend); }
public async Task SenderReceiver_WhenBoundAndConnected_PassesMessage() { // Arrange var responseStr = "Hello, World!"; var requestStr = "Hello"; var receivedRequest = string.Empty; ushort port = 6555; var called = false; mockRequestDispatcher .Setup(m => m.Handle(ref It.Ref <RequestTask> .IsAny)) .Callback(new Handler((ref RequestTask task) => { called = true; receivedRequest = (string)task.Request; task.ResponseSender(responseStr); })); var packageFactory = new PackageFactory(); var serializer = new DotNetSerializer(); var serializerCache = new SerializerCache(); var messageFactory = new NetMQMessageFactory(serializerCache, packageFactory); var sender = new NetMQSender(new DealerSocket(), messageFactory); var receiver = new NetMQReceiver(new RouterSocket(), messageFactory, requestDispatcher); var poller = new NetMQPoller(); serializerCache.AddSerializer(serializer); sender.AddAddress(TcpAddress.Localhost(port)); sender.InitializeConnection(); receiver.AddAddress(TcpAddress.Wildcard(port)); receiver.InitializeConnection(); poller.Add(sender.PollableSocket); poller.Add(receiver.PollableSocket); poller.RunAsync(); var package = new DataPackage <string>(new GuidPackageId(), requestStr); // Act var response = await sender.SendAndReceive(package, TimeSpan.FromSeconds(5)); // Cleanup poller.StopAsync(); sender.TerminateConnection(); receiver.TerminateConnection(); // Assert Assert.That(called, Is.True); Assert.That(receivedRequest, Is.EqualTo(requestStr)); Assert.That((string)response, Is.EqualTo(responseStr)); }
private void StartQueryMQ() { //request string ipAddress = System.Configuration.ConfigurationManager.AppSettings["AlyServerAddress"]; string queryPort = System.Configuration.ConfigurationManager.AppSettings["AlyServerQueryPort"]; //pub string[] selfParams = selfPubZmqParams.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string pubAddress = string.Format("tcp://{0}:{1}", selfParams[5], selfParams[1]); string resAddress = string.Format("tcp://{0}:{1}", selfParams[5], selfParams[3]); if (!string.IsNullOrEmpty(ipAddress) && !string.IsNullOrEmpty(queryPort) ) { string address = string.Format("tcp://{0}:{1}", ipAddress, queryPort); try { if (_resSocket == null) { _resSocket = new ResponseSocket(); _resSocket.ReceiveReady += _resSocket_ReceiveReady; _resSocket.SendReady += _resSocket_SendReady; _resSocket.Bind(address); } if (_publisher == null) { _publisher = new PublisherSocket(); _publisher.Bind(pubAddress); _publisher.SendReady += _publisher_SendReady; } if (_resPoller == null) { _resPoller = new NetMQPoller(); _resPoller.Add(_resSocket); _resPoller.Add(_publisher); _resPoller.RunAsync(); Console.WriteLine("[Progress]:[1]Pub Response Listening"); } } catch (Exception ex) { throw ex; } } }
public void Run(PairSocket shim) { _poller = new NetMQPoller(); _ = Observable.FromEventPattern <NetMQSocketEventArgs>(e => shim.ReceiveReady += e, e => shim.ReceiveReady -= e) .Select(e => e.EventArgs) .Subscribe(OnShimReady); _poller.Add(shim); // Timer var timeoutTimer = new NetMQTimer(TimeSpan.FromSeconds(5)); _ = Observable.FromEventPattern <NetMQTimerEventArgs>(e => timeoutTimer.Elapsed += e, e => timeoutTimer.Elapsed -= e) .Select(e => e.EventArgs) .ObserveOn(ThreadPoolScheduler.Instance) .Subscribe(OnTimeoutElapsed); _poller.Add(timeoutTimer); _subscriberSocket = new SubscriberSocket(); _subscriberSocket.Options.Linger = TimeSpan.Zero; _subscriberSocket.Subscribe(CoreHearbeatTopic); _subscriberSocket.Connect($"tcp://{_address}:{_port + 1}"); _subject.OnNext(ConnectionStatus.Connecting); _ = Observable.FromEventPattern <NetMQSocketEventArgs>(e => _subscriberSocket.ReceiveReady += e, e => _subscriberSocket.ReceiveReady -= e) .Select(e => e.EventArgs) .Where(e => e.Socket.ReceiveFrameString() == CoreHearbeatTopic) .ObserveOn(ThreadPoolScheduler.Instance) .Subscribe(e => { timeoutTimer.Reset(); Thread.MemoryBarrier(); var status = _borgConnected ? (ConnectionStatus.Online | ConnectionStatus.Connected) : (ConnectionStatus.Online | ConnectionStatus.Disconnected); _subject.OnNext(status); }); _poller.Add(_subscriberSocket); timeoutTimer.Reset(); shim.SignalOK(); _poller.Run(); // Cleanup stuff after stopping _poller.Remove(_subscriberSocket); _poller.Remove(timeoutTimer); _poller.Remove(shim); _poller.Dispose(); }
public async Task Start() { _nodeSocket = new PushSocket(_localConnectionString); _poller.Add(_nodeSocket); _poller.RunAsync(); _active = true; foreach (var connStr in _peerConnectionStrings) { PullSocket peer = new PullSocket(connStr); peer.ReceiveReady += Peer_ReceiveReady; _poller.Add(peer); _peerSockets.Add(peer); } }
/// <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}"); }
public (bool success, Exception ex) Setup() { Exception exception = null; try { _socketDelegate = async(s, arg) => await HandleAsync(); _socket.ReceiveReady += _socketDelegate; // todo use actual topics instead of catchall string catchAllTopic = ""; _socket.Bind(_configuration.Address()); _socket.Subscribe(catchAllTopic); _configuration.Logger.Log(new DebugLogMsg($"subscribed to [{typeof(TMessage)}]")); _poller.Add(_socket); _poller.RunAsync(); return(true, null); } catch (NetMQ.EndpointNotFoundException ntfnd) { _configuration.Logger.Log(new ErrorLogMsg(ntfnd.Message)); exception = ntfnd; return(false, exception); } }
static void Main(string[] args) { using (var router = new WSRouter()) { using (var publisher = new WSPublisher()) { router.Bind("ws://localhost:80"); publisher.Bind("ws://localhost:81"); router.ReceiveReady += (sender, eventArgs) => { var identity = eventArgs.WSSocket.ReceiveFrameBytes(); using (var datasendercontext = new DataSenderContext()) { datasendercontext.Start(eventArgs, publisher, new Identity() { Receiver = identity }); } }; var poller = new NetMQPoller(); poller.Add(router); poller.Run(); } } }
// Start is called before the first frame update public void Start() { SetDefaultListenerPosition(); string[] args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { Debug.Log("ARG " + i + ": " + args[i]); if (args[i].Contains("ignitebot")) { isIgniteBotEmbedded = true; break; } } playerObject = GameObject.Find("Player Listener"); if (isIgniteBotEmbedded) { AsyncIO.ForceDotNet.Force(); NetMQConfig.Cleanup(); poller = new NetMQPoller(); subSocket = new SubscriberSocket(); subSocket.ReceiveReady += OnReceiveReady; subSocket.Options.ReceiveHighWatermark = 10; subSocket.Connect(addr); subSocket.Subscribe("RawFrame"); subSocket.Subscribe("CloseApp"); subSocket.Subscribe("MatchEvent"); poller.Add(subSocket); poller.RunAsync(); } }
public void Receive_BrokerDisconnectedWithLogging_ShouldReturnRequest() { const string hostAddress = "tcp://localhost:5555"; var loggingMessages = new List <string> (); // setup the counter socket for communication using (var broker = new RouterSocket()) using (var poller = new NetMQPoller()) using (var session = new MDPWorker(hostAddress, "test")) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors but don't answer broker.ReceiveReady += (s, e) => e.Socket.ReceiveMultipartMessage(); poller.Add(broker); poller.RunAsync(); // speed up the test session.HeartbeatDelay = TimeSpan.FromMilliseconds(250); session.ReconnectDelay = TimeSpan.FromMilliseconds(250); // set the event handler to receive the logging messages session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info); // initialise the worker - broker protocol session.Receive(null); poller.Stop(); Assert.That(loggingMessages.Count(m => m.Contains("retrying")), Is.EqualTo(3)); // 3 times retrying and 1 time initial connecting Assert.That(loggingMessages.Count(m => m.Contains("localhost")), Is.EqualTo(4)); Assert.That(loggingMessages.Last().Contains("abandoning")); } }
private void Run(PairSocket shim) { using (m_publisherSocket = new XPublisherSocket(m_address)) { m_publisherSocket.SetWelcomeMessage(WelcomeMessage); m_publisherSocket.ReceiveReady += DropPublisherSubscriptions; m_heartbeatTimer = new NetMQTimer(HeartbeatInterval); m_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed; shim.ReceiveReady += OnShimMessage; // signal the actor that the shim is ready to work shim.SignalOK(); m_poller = new NetMQPoller { m_publisherSocket, shim }; m_poller.Add(m_heartbeatTimer); // Polling until poller is cancelled m_poller.Run(); } }
public void Send_WrongServiceNameWithLogging_ShouldLogPermanentError() { const string hostAddress = "tcp://localhost:5555"; var loggingMessages = new List <string>(); // setup the counter socket for communication using (var broker = new RouterSocket()) using (var poller = new NetMQPoller()) using (var session = new MDPClient(hostAddress)) { broker.Bind(hostAddress); // we need to pick up any message in order to avoid errors broker.ReceiveReady += (s, e) => { // just swallow message -> wrong service name e.Socket.ReceiveMultipartMessage(); }; poller.Add(broker); poller.RunAsync(); // set the event handler to receive the logging messages session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info); // well formed message var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") }); // wrong service name session.Send("xyz", requestMessage); poller.Stop(); Assert.That(loggingMessages.Count, Is.EqualTo(7)); Assert.That(loggingMessages[6], Is.EqualTo("[CLIENT ERROR] permanent error, abandoning!")); } }
private void StartQueryMQ() { this.Options = Options.LoadFromAppSettings(); string serverAddress = System.Configuration.ConfigurationManager.AppSettings["AlyServerAddress"]; string queryPort = System.Configuration.ConfigurationManager.AppSettings["AlyServerQueryPort"]; if (!string.IsNullOrEmpty(serverAddress) && !string.IsNullOrEmpty(queryPort) ) { string addressUrl = string.Format("tcp://{0}:{1}", serverAddress, queryPort); try { if (null == _querySocket) { _querySocket = new RequestSocket(); _querySocket.ReceiveReady += _querySocket_ReceiveReady; _querySocket.SendReady += _querySocket_SendReady; } if (null == _queryPoller) { _queryPoller = new NetMQPoller(); _queryPoller.Add(_querySocket); _querySocket.Connect(addressUrl); _queryMsgList.Clear(); _queryPoller.RunAsync(); Console.WriteLine("[Progress]:[1] Request Listening"); } } catch (Exception ex) { } } }
/// <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; }
public void Run(params string[] addresses) { var subscriber = Connect(addresses); if (subscriber == null) { throw new Exception("cannot connect to eny of the endpoints"); } // timeout timer, when heartbeat was not arrived for 5 seconds m_timeoutTimer = new NetMQTimer(TimeSpan.FromSeconds(5)); m_timeoutTimer.Elapsed += (sender, args) => { // timeout happend, first dispose existing subscriber subscriber.Dispose(); m_poller.Remove(subscriber); // connect again subscriber = Connect(addresses); if (subscriber == null) { throw new Exception("cannot connect to eny of the endpoints"); } m_poller.Add(subscriber); }; m_poller = new NetMQPoller { subscriber }; m_poller.Add(m_timeoutTimer); m_poller.Run(); }
/// <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 Initialize() { running = true; cancellationToken = cts.Token; processIncomingMessages = Task.Factory.StartNew(() => { // instantiate poller and socket poller = new NetMQPoller(); socket = new DealerSocket(); socket.Options.Identity = Encoding.UTF8.GetBytes(clientID); // socket needs clientID for communication Dealer-Router socket.ReceiveReady += OnMessage; // event on receive data StartSocket(); poller.Add(socket); poller.RunAsync(); while (running) { Thread.Sleep(delay); if (cancellationToken.IsCancellationRequested) { Debug.Log("Cancelling task"); break; } } }, cancellationToken); }
public void StartSending(int id) { client.Options.Identity = Encoding.Unicode.GetBytes(id.ToString()); var message = string.Format("Id = {0}", id.ToString()); var bytes = Encoding.ASCII.GetBytes(message); using (var poller = new NetMQPoller()) { poller.Add(client); poller.Add(messageQueue); poller.RunAsync(); var messageToServer = new NetMQMessage(); messageToServer.Append(message); messageQueue.Enqueue(messageToServer); } }
public Server(App app) { _App = app; _poller = new NetMQPoller(); _responseSocket = new ResponseSocket(); _responseSocket.ReceiveReady += OnReceiveReady; _poller.Add(_responseSocket); }
/// <summary> /// Start node, after setting header values. When you start a node it /// begins discovery and connection. /// </summary> public void Start() { if (_useEvents) { _inboxPoller.Add(_inbox); Thread.Sleep(100); } _actor.SendMoreFrame("START").SendFrame(_interfaceName ?? ""); }
private static async Task CreatePushSocket() { var poller = new NetMQPoller(); push = new PushSocket(); push.BindRandomPort("tcp://127.0.0.1"); NetMQMonitor monitor = new NetMQMonitor(push, "inproc://req.inproc", SocketEvents.All); monitor.Connected += Monitor_Connected; monitor.EventReceived += Monitor_EventReceived; //monitor.AttachToPoller(poller); queue.ReceiveReady += Queue_ReceiveReady;; push.Connect(address); poller.Add(push); poller.Add(queue); poller.RunAsync(); await monitor.StartAsync(); }
public Task StartAsync(HostingApplication hostingApplication, CancellationToken cancellationToken) { _routerSocket = new RouterSocket(); _routerSocket.Bind($"tcp://{_hostingOptions.Host}"); _routerSocket.ReceiveReady += RouterSocket_ReceiveReady; _dealerSocket = new DealerSocket(); _dealerSocket.Bind(INPROC_SERVER_URL); _dealerSocket.ReceiveReady += DealerSocket_ReceiveReady; _poller = new NetMQPoller { _routerSocket, _dealerSocket }; _poller.RunAsync(); _workerPoller = new NetMQPoller(); async void OnReceiveReady(object sender, NetMQSocketEventArgs args) { NetMQMessage receiveMessage = args.Socket.ReceiveMultipartMessage(); string address = receiveMessage.Pop().ConvertToString(); string content = receiveMessage.Last().ConvertToString(Encoding.UTF8); OwinContext owinContext = null; long startTimestamp = Stopwatch.GetTimestamp(); _logger.LogInformation($"Request starting tcp://{_hostingOptions.Host} {content}"); owinContext = hostingApplication.CreateContext(content); try { await hostingApplication.ProcessRequestAsync(owinContext); } catch (Exception ex) { owinContext.Response.Error(ex.Message); throw; } finally { string sendContent = _serializer.Serialize(owinContext.Response); _logger.LogInformation($"Request finished in {new TimeSpan((long)(TimestampToTicks * (Stopwatch.GetTimestamp() - startTimestamp))).TotalMilliseconds}ms {sendContent}"); NetMQMessage sendMessage = new NetMQMessage(); sendMessage.Append(address); sendMessage.AppendEmptyFrame(); sendMessage.Append(sendContent, Encoding.UTF8); args.Socket.SendMultipartMessage(sendMessage); hostingApplication.DisponseContext(owinContext); } } foreach (var item in Enumerable.Range(0, _hostingOptions.ProcessCount)) { NetMQSocket process = new DealerSocket(); process.Connect(INPROC_SERVER_URL); process.ReceiveReady += OnReceiveReady; _workerPoller.Add(process); } _workerPoller.RunAsync(); return(Task.CompletedTask); }
void IShimHandler.Run(PairSocket shim) { Poller = new NetMQPoller(); Shim = shim; Shim.ReceiveReady += OnShimReady; Poller.Add(Shim); Initialize(); Shim.SignalOK(); Poller.Run(); Cleanup(); }
public void RemoveTimer() { using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) using (var poller = new NetMQPoller { router }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool timerTriggered = false; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (s, a) => { timerTriggered = true; }; // The timer will fire after 100ms poller.Add(timer); bool messageArrived = false; router.ReceiveReady += (s, e) => { router.SkipFrame(); router.SkipFrame(); messageArrived = true; // Remove timer poller.Remove(timer); }; poller.RunAsync(); Thread.Sleep(20); dealer.SendFrame("hello"); Thread.Sleep(300); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsFalse(timerTriggered); } }
public void Router_Dealer_Demonstrating_Messages_From_Subscribers_To_Publisher() { // NOTES // 1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server // 2. Each thread can send using it own socket // 3. Each thread socket is added to poller const int delay = 500; // millis var clientSocketPerThread = new ThreadLocal<DealerSocket>(); using (var server = new RouterSocket("@tcp://127.0.0.1:5556")) { using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. for (int i = 0; i < 4; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect("tcp://127.0.0.1:5556"); client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } while (true) { NetMQMessage messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(state.ToString()); Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE TO SERVER "); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); client.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } // start the poller poller.RunAsync(); // server loop for(int i=0;i<6;i++) { NetMQMessage clientMessage = server.ReceiveMessage(); Console.WriteLine("======================================"); Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT "); Console.WriteLine("======================================"); PrintFrames("Server receiving", clientMessage); if (clientMessage.FrameCount == 3) { var clientAddress = clientMessage[0]; var clientOriginalMessage = clientMessage[2].ConvertToString(); string response = string.Format("{0} back from server {1}", clientOriginalMessage, DateTime.Now.ToLongTimeString()); var messageToClient = new NetMQMessage(); messageToClient.Append(clientAddress); messageToClient.AppendEmptyFrame(); messageToClient.Append(response); server.SendMultipartMessage(messageToClient); } } } } }
public void Router_Dealer_Demonstrating_Messages_From_Publisher_To_Subscribers() { // NOTES // 1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server // 2. Each thread can send using it own socket // 3. Each thread socket is added to poller const int delay = 500; // millis var clientSocketPerThread = new ThreadLocal<DealerSocket>(); string endpoint; using (var server = new RouterSocket("@tcp://127.0.0.1:0")) // If we specify 0, it will choose a random port for us. { endpoint = server.Options.LastEndpoint; // Lets us know which port was chosen. Console.Write("Last endpoint, including port: {0}\n", server.Options.LastEndpoint); using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. for (int i = 0; i < 4; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect(endpoint); //client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } Thread.Sleep(3000); // Wait until server is up. client.SendFrame("Ping"); while (true) { Console.Write("Client {0}: Waiting for ping...\n", i); // Work around "feature" of router/dealer: the publisher does not know the subscriber exists, until it // sends at least one message which makes it necessary to open the connection. I believe this is a // low-level feature of the TCP/IP transport. var clientMessage = client.ReceiveMultipartMessage(); Console.WriteLine("======================================"); Console.WriteLine(" INCOMING CLIENT MESSAGE FROM SERVER"); Console.WriteLine("======================================"); PrintFrames("Server receiving", clientMessage); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } // start the poller poller.RunAsync(); // server loop int sequenceNo = 0; for (int i=0;i<10;i++) { NetMQMessage messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(sequenceNo.ToString()); sequenceNo++; Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE {0} TO CLIENTS ", sequenceNo); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); server.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } Console.WriteLine("Finished."); } } }
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 SimpleTimer() { // TODO it is not really clear what this test is actually testing -- maybe split it into a few smaller tests using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) using (var poller = new NetMQPoller { router }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool messageArrived = false; router.ReceiveReady += (s, e) => { Assert.IsFalse(messageArrived); router.SkipFrame(); router.SkipFrame(); messageArrived = true; }; bool timerTriggered = false; int count = 0; const int timerIntervalMillis = 100; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); timer.Elapsed += (s, a) => { // the timer should jump before the message Assert.IsFalse(messageArrived); timerTriggered = true; timer.Enable = false; count++; }; poller.Add(timer); poller.RunAsync(); Thread.Sleep(150); dealer.SendFrame("hello"); Thread.Sleep(300); poller.Stop(); Assert.IsTrue(messageArrived); Assert.IsTrue(timerTriggered); Assert.AreEqual(1, count); } }
public void AddSocketDuringWork() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var poller = new NetMQPoller { router1 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); bool router1Arrived = false; bool router2Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1.SkipFrame(); router1.SkipFrame(); router1Arrived = true; poller.Add(router2); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2.SkipFrame(); router2.SkipFrame(); router2Arrived = true; signal2.Set(); }; poller.RunAsync(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); poller.Stop(); Assert.IsTrue(router1Arrived); Assert.IsTrue(router2Arrived); } }
public void NativeSocket() { using (var streamServer = new StreamSocket()) using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = streamServer.BindRandomPort("tcp://*"); socket.Connect("127.0.0.1", port); var buffer = new byte[] { 1 }; socket.Send(buffer); byte[] identity = streamServer.ReceiveFrameBytes(); byte[] message = streamServer.ReceiveFrameBytes(); Assert.AreEqual(buffer[0], message[0]); var socketSignal = new ManualResetEvent(false); using (var poller = new NetMQPoller()) { poller.Add(socket, s => { socket.Receive(buffer); socketSignal.Set(); // removing the socket poller.Remove(socket); }); poller.RunAsync(); // no message is waiting for the socket so it should fail Assert.IsFalse(socketSignal.WaitOne(100)); // sending a message back to the socket streamServer.SendMoreFrame(identity).SendFrame("a"); Assert.IsTrue(socketSignal.WaitOne(100)); socketSignal.Reset(); // sending a message back to the socket streamServer.SendMoreFrame(identity).SendFrame("a"); // we remove the native socket so it should fail Assert.IsFalse(socketSignal.WaitOne(100)); poller.Stop(); } } }
public void TestPollerDispose() { const int timerIntervalMillis = 10; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)); var signal = new ManualResetEvent(false); var count = 0; timer.Elapsed += (s, a) => { if (count++ == 5) signal.Set(); }; NetMQPoller poller; using (poller = new NetMQPoller { timer }) { poller.RunAsync(); Assert.IsTrue(signal.WaitOne(500)); Assert.IsTrue(poller.IsRunning); Assert.Throws<InvalidOperationException>(() => poller.Run()); } Assert.IsFalse(poller.IsRunning); Assert.Throws<ObjectDisposedException>(() => poller.Run()); Assert.Throws<ObjectDisposedException>(() => poller.Stop()); Assert.Throws<ObjectDisposedException>(() => poller.Add(timer)); Assert.Throws<ObjectDisposedException>(() => poller.Remove(timer)); }