private static Message GetNextMessage() { var message = new Message(); // There may be additional ZMQ identities attached; read until the delimiter <IDS|MSG>" // and store them in message.identifiers // http://ipython.org/ipython-doc/dev/development/messaging.html#the-wire-protocol var delimAsBytes = Encoding.ASCII.GetBytes(Constants.Delimiter); while (true) { var delim = ShellRouterSocket.ReceiveFrameBytes(); if (delim.SequenceEqual(delimAsBytes)) { break; } message.Identifiers.Add(delim); } // Getting Hmac message.HMac = ShellRouterSocket.ReceiveFrameString(); Log.Info(message.HMac); // Getting Header var header = ShellRouterSocket.ReceiveFrameString(); Log.Info(header); message.Header = JsonSerializer.Deserialize <Header>(header); // Getting parent header var parentHeader = ShellRouterSocket.ReceiveFrameString(); Log.Info(parentHeader); message.ParentHeader = JsonSerializer.Deserialize <Header>(parentHeader); // Getting metadata var metadata = ShellRouterSocket.ReceiveFrameString(); Log.Info(metadata); message.Metadata = JsonSerializer.Deserialize <Dictionary <string, object> >(metadata); // Getting content var content = ShellRouterSocket.ReceiveFrameString(); Log.Info(content); message.Content = content; return(message); }
public void Execute() { using (var reporterFinisher = new PublisherSocket(PUBLISHER)) using (var jobFinisher = new RouterSocket(ROUTER)) { Console.WriteLine("Finisher ONNNNNNNNNNNNNNNNNN"); Console.WriteLine($"Listening running on: {ROUTER}"); while (true) { try { var identity = jobFinisher.ReceiveFrameString(); Console.WriteLine("identity: " + identity); var message = jobFinisher.ReceiveFrameString(); Console.WriteLine("message: " + message); var envelope = Newtonsoft.Json.JsonConvert.DeserializeObject <Envelope>(message); if (_validatedMessages.ContainsKey(envelope.Identity)) { var validatedMessage = _validatedMessages[envelope.Identity]; Console.WriteLine("Localizado " + envelope.Identity); validatedMessage.Count++; validatedMessage.Message.ValidationMessages.AddRange(envelope.ValidationMessages); if (validatedMessage.Count == 3) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(validatedMessage.Message); reporterFinisher.SendMoreFrame(envelope.Identity).SendFrame(json); Console.WriteLine("Finisher sending " + envelope.Identity); _setCachedValueCommand.Execute(new SetCacheParameter(envelope.Identity, json)); _validatedMessages.Remove(envelope.Identity); } } else { Console.WriteLine("Criado " + envelope.Identity); var validated = new ValidatedMessage(envelope); validated.Count++; _validatedMessages.Add(envelope.Identity, validated); } } catch (Exception ex) //Drop message { Console.WriteLine("Erro na validação do dado: " + ex.Message); } } } }
public void HasInTest() { using (var server = new RouterSocket()) using (var client = new DealerSocket()) { var port = server.BindRandomPort("tcp://*"); // no one sent a message so it should be false Assert.IsFalse(server.HasIn); client.Connect("tcp://localhost:" + port); // wait for the client to connect Thread.Sleep(100); // now we have one client connected but didn't send a message yet Assert.IsFalse(server.HasIn); client.SendFrame("1"); // wait for the message to arrive Thread.Sleep(100); // the has in should indicate a message is ready Assert.IsTrue(server.HasIn); server.SkipFrame(); // identity string message = server.ReceiveFrameString(); Assert.AreEqual(message, "1"); // we read the message, it should false again Assert.IsFalse(server.HasIn); } }
public void Messages_From_Router_To_Dealer() { Console.Write("Test sending message from publisher(router) to subscribers (dealer).\n"); var maxMessage = 5; var cd = new CountdownEvent(maxMessage); string endpoint; using (var publisher = new RouterSocket()) using (var subscriber = new DealerSocket()) using (var poller = new NetMQPoller { subscriber }) { publisher.Bind("tcp://127.0.0.1:0"); endpoint = publisher.Options.LastEndpoint; subscriber.Connect(endpoint); subscriber.ReceiveReady += (sender, e) => { var strs = e.Socket.ReceiveMultipartStrings(); foreach (var str in strs) { Console.WriteLine("Subscribe: " + str); } cd.Signal(); }; var clientId = Encoding.Unicode.GetBytes("ClientId"); subscriber.Options.Identity = clientId; const string request = "Ping"; // 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. subscriber.SendFrame(request); // Ping. var serverId = publisher.ReceiveFrameBytes(); Assert.AreEqual(request, publisher.ReceiveFrameString()); for (var i = 0; i < maxMessage; i++) { var msg = string.Format("[message: {0}]", i); Console.Write("Publish: {0}\n", msg); publisher.SendMoreFrame(serverId).SendFrame(msg); } poller.RunAsync(); if (cd.Wait(TimeSpan.FromSeconds(10)) == false) // Blocks until _countdown.Signal has been called. { Assert.Fail("Timed out, this test should complete in less than 10 seconds."); } } }
void VentilatorCommand_SendCommand(DealerSocket ventilatorCommand, RouterSocket command) { #region communication ventilatorCommand to Commander var msgCommand = new NetMQMessage(); msgCommand.AppendEmptyFrame(); msgCommand.Append("HELLO"); ventilatorCommand.SendMultipartMessage(msgCommand); _testOutputHelper.WriteLine("Send Hello to command processor"); Task.Delay(1000); var messageCommandID = command.ReceiveFrameString(); command.ReceiveFrameString(); var messageCommandCommand = command.ReceiveFrameString(); _testOutputHelper.WriteLine("Received Command: {0} {1}", messageCommandID, messageCommandCommand); #endregion }
void VentilatorQuery_SendQuery(DealerSocket ventilatorQuery, RouterSocket query) { #region communication ventilatorQuery to Querier var msgQuery = new NetMQMessage(); msgQuery.AppendEmptyFrame(); msgQuery.Append("HELLO"); ventilatorQuery.SendMultipartMessage(msgQuery); _testOutputHelper.WriteLine("Send Hello to query processor"); Task.Delay(1000); var messageQueryID = query.ReceiveFrameString(); query.ReceiveFrameString(); var messageQueryCommand = query.ReceiveFrameString(); _testOutputHelper.WriteLine("Received Query: {0} {1}", messageQueryID, messageQueryCommand); #endregion }
public void Messages_From_Dealer_To_Router() { var maxMessage = 5; var cd = new CountdownEvent(maxMessage); Console.Write("Test sending message from subscribers (dealer) to publisher(router).\n"); using (var publisher = new RouterSocket()) using (var subscriber = new DealerSocket()) using (var poller = new NetMQPoller { subscriber }) { var port = publisher.BindRandomPort("tcp://*"); subscriber.Connect("tcp://127.0.0.1:" + port); subscriber.ReceiveReady += (sender, e) => { var strs = e.Socket.ReceiveMultipartStrings(); foreach (var str in strs) { Console.WriteLine(str); } cd.Signal(); }; var clientId = Encoding.Unicode.GetBytes("ClientId"); subscriber.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!"; subscriber.SendFrame(request); var serverId = publisher.ReceiveFrameBytes(); Assert.AreEqual(request, publisher.ReceiveFrameString()); for (var i = 0; i < maxMessage; i++) { publisher.SendMoreFrame(serverId).SendFrame(response); } poller.RunAsync(); if (cd.Wait(TimeSpan.FromSeconds(10)) == false) // Blocks until _countdown.Signal has been called. { Assert.Fail("Timed out, this test should complete in less than 10 seconds."); } } }
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 static void Main() { var workers = new List<Thread>(WorkersCount); using (var client = new RouterSocket()) { string cnn = $"tcp://localhost:{PortNumber}"; client.Bind(cnn); Console.WriteLine("[B] Connect to {0}", cnn); for (int workerNumber = 0; workerNumber < WorkersCount; workerNumber++) { workers.Add(new Thread(WorkerTask)); workers[workerNumber].Start(PortNumber); } for (int taskNumber = 0; taskNumber < WorkersCount*10; taskNumber++) { // LRU worker is next waiting in queue string address = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", address); string empty = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", empty); string ready = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", ready); client.SendMoreFrame(address); //Console.WriteLine("[B] Message sent: {0}", address); client.SendMoreFrame(""); //Console.WriteLine("[B] Message sent: {0}", ""); client.SendFrame("This is the workload"); //Console.WriteLine("[B] Message sent: {0}", "This is the workload"); } // Now ask mamas to shut down and report their results for (int taskNbr = 0; taskNbr < WorkersCount; taskNbr++) { string address = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", address); string empty = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", empty); string ready = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", ready); client.SendMoreFrame(address); //Console.WriteLine("[B] Message sent: {0}", address); client.SendMoreFrame(""); //Console.WriteLine("[B] Message sent: {0}", ""); client.SendFrame("END"); //Console.WriteLine("[B] Message sent: {0}", "END"); } } Console.ReadLine(); }
public static void Main() { var workers = new List <Thread>(WorkersCount); using (var client = new RouterSocket()) { string cnn = $"tcp://localhost:{PortNumber}"; client.Bind(cnn); Console.WriteLine("[B] Connect to {0}", cnn); for (int workerNumber = 0; workerNumber < WorkersCount; workerNumber++) { workers.Add(new Thread(WorkerTask)); workers[workerNumber].Start(PortNumber); } for (int taskNumber = 0; taskNumber < WorkersCount * 10; taskNumber++) { // LRU worker is next waiting in queue string address = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", address); string empty = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", empty); string ready = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", ready); client.SendMoreFrame(address); //Console.WriteLine("[B] Message sent: {0}", address); client.SendMoreFrame(""); //Console.WriteLine("[B] Message sent: {0}", ""); client.SendFrame("This is the workload"); //Console.WriteLine("[B] Message sent: {0}", "This is the workload"); } // Now ask mamas to shut down and report their results for (int taskNbr = 0; taskNbr < WorkersCount; taskNbr++) { string address = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", address); string empty = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", empty); string ready = client.ReceiveFrameString(); //Console.WriteLine("[B] Message received: {0}", ready); client.SendMoreFrame(address); //Console.WriteLine("[B] Message sent: {0}", address); client.SendMoreFrame(""); //Console.WriteLine("[B] Message sent: {0}", ""); client.SendFrame("END"); //Console.WriteLine("[B] Message sent: {0}", "END"); } } Console.ReadLine(); }
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) => { var strs = e.Socket.ReceiveMultipartStrings(); foreach (var str in strs) { Console.WriteLine(str); } 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(); } }
public void Handover() { using (var router = new RouterSocket()) using (var dealer1 = new DealerSocket()) { router.Options.RouterHandover = true; router.Bind("inproc://127.0.0.1:5555"); dealer1.Options.Identity = Encoding.ASCII.GetBytes("ID"); dealer1.Connect("inproc://127.0.0.1:5555"); dealer1.SendMoreFrame("Hello").SendFrame("World"); var identity = router.ReceiveFrameString(); Assert.AreEqual("ID", identity); using (var dealer2 = new DealerSocket()) { dealer2.Options.Identity = Encoding.ASCII.GetBytes("ID"); dealer2.Connect("inproc://127.0.0.1:5555"); // We have new peer which should take over, however we are still reading a message var message = router.ReceiveFrameString(); Assert.AreEqual("Hello", message); message = router.ReceiveFrameString(); Assert.AreEqual("World", message); dealer2.SendMoreFrame("Hello").SendFrame("World"); identity = router.ReceiveFrameString(); Assert.AreEqual("ID", identity); message = router.ReceiveFrameString(); Assert.AreEqual("Hello", message); message = router.ReceiveFrameString(); Assert.AreEqual("World", message); } } }
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); } }
void ClientCommand_Ventilator(DealerSocket client, RouterSocket ventilator, DealerSocket ventilatorCommand, RouterSocket command) { // inicialização das conexões ventilator -> command executor // var commandHello = new NetMQMessage(); // commandHello.AppendEmptyFrame(); // commandHello.Append("HELLO"); // ventilatorCommand.SendMultipartMessage(commandHello); // _testOutputHelper.WriteLine("Send Hello to command processor"); // // Task.Delay(1000); // // var hello = command.ReceiveFrameString(); // command.ReceiveFrameString(); // var helloCommand = command.ReceiveFrameString(); // _testOutputHelper.WriteLine("Received Command: {0} {1}", hello, helloCommand); // client envia comando var commandData = new NetMQMessage(); commandData.AppendEmptyFrame(); commandData.Append("COMMAND"); commandData.Append("COMMAND_DATA"); client.SendMultipartMessage(commandData); _testOutputHelper.WriteLine("Client send a command to ventilator"); Task.Delay(1000); var senderId = ventilator.ReceiveFrameString(); ventilator.ReceiveFrameString(); var requestType = ventilator.ReceiveFrameString(); var messageCommandData = ventilator.ReceiveFrameString(); _testOutputHelper.WriteLine("Ventilator Received Request: {0} {1} {2}", senderId, requestType, messageCommandData); Task.Delay(1000); // ventilator roteia comando var routingCommandData = new NetMQMessage(); routingCommandData.AppendEmptyFrame(); routingCommandData.Append(messageCommandData); ventilatorCommand.SendMultipartMessage(routingCommandData); _testOutputHelper.WriteLine("Ventilator send a command to command processor"); Task.Delay(1000); var sender = command.ReceiveFrameString(); command.ReceiveFrameString(); var receiveCommandData = command.ReceiveFrameString(); _testOutputHelper.WriteLine("Command Received sender: {0} command args: {1}", sender, receiveCommandData); // Task.Delay(1000); // // var commandAnswerData = new NetMQMessage(); // commandAnswerData.AppendEmptyFrame(); // commandAnswerData.Append(messageCommandData + ": OK"); // command.SendMultipartMessage(commandAnswerData); // _testOutputHelper.WriteLine("Command send an answer to ventilator"); // // Task.Delay(1000); // var senderCommand = ventilatorCommand.ReceiveFrameString(); // ventilatorCommand.ReceiveFrameString(); // var receiveCommandAnswer = ventilatorCommand.ReceiveFrameString(); // _testOutputHelper.WriteLine("Ventilator Received Command Answer: {0} command args: {1}", sender, receiveCommandAnswer); // // Task.Delay(1000); // // var routeAnswerData = new NetMQMessage(); // routeAnswerData.AppendEmptyFrame(); // routeAnswerData.Append(messageCommandData + ": OK"); // ventilator.SendMultipartMessage(commandAnswerData); // _testOutputHelper.WriteLine("Command send an answer to ventilator"); // // Task.Delay(1000); // // var senderCommand = ventilatorCommand.ReceiveFrameString(); // ventilatorCommand.ReceiveFrameString(); // var receiveCommandAnswer = ventilatorCommand.ReceiveFrameString(); // _testOutputHelper.WriteLine("Ventilator Received Command Answer: {0} command args: {1}", sender, receiveCommandAnswer); }