Ejemplo n.º 1
0
 private static void Queue_ReceiveReady(object sender, NetMQQueueEventArgs <byte[]> e)
 {
     if (e.Queue.TryDequeue(out byte[] result, TimeSpan.FromSeconds(1.0)))
     {
         push.SendFrame(result);
     }
 }
Ejemplo n.º 2
0
 static void Main(string[] args)
 {
     /// Task Ventilator
     // Binds PUSH socket to tcp://localhost:5557
     // Sends batch of tasks to workers via that socket
     Console.WriteLine("====== VENTILATOR ======");
     using (var sender = new PushSocket("@tcp://*:5557"))
         using (var sink = new PushSocket(">tcp://localhost:5558"))
         {
             Console.WriteLine("Press enter when worker are ready");
             Console.ReadLine();
             //the first message it "0" and signals start of batch
             //see the Sink.csproj Program.cs file for where this is used
             Console.WriteLine("Sending start of batch to Sink");
             sink.SendFrame("0");
             Console.WriteLine("Sending tasks to workers");
             //initialise random number generator
             Random rand = new Random(0);
             //expected costs in Ms
             int totalMs = 0;
             //send 100 tasks (workload for tasks, is just some random sleep time that
             //the workers can perform, in real life each work would do more than sleep
             for (int taskNumber = 0; taskNumber < 100; taskNumber++)
             {
                 //Random workload from 1 to 100 msec
                 int workload = rand.Next(0, 100);
                 totalMs += workload;
                 Console.WriteLine("Workload : {0}", workload);
                 sender.SendFrame(workload.ToString());
             }
             Console.WriteLine("Total expected cost : {0} msec", totalMs);
             Console.WriteLine("Press Enter to quit");
             Console.ReadLine();
         }
 }
Ejemplo n.º 3
0
 static void Main(string[] args)
 {
     // Task Ventilator
     // Binds PUSH socket to tcp://localhost:5557
     // Sends batch of tasks to workers via that socket
     Console.WriteLine("====== VENTILATOR ======");
     using (var sender = new PushSocket("@tcp://*:80"))
         using (var sink = new PullSocket(">tcp://localhost:8080"))
         {
             Thread.Sleep(1000);
             //the first message it "0" and signals start of batch
             //see the Sink.csproj Program.cs file for where this is used
             Console.WriteLine("Sending start of batch to Sink");
             //sink.SendFrame("0");
             Console.WriteLine("Sending tasks to workers");
             //initialise random number generator
             Random rand = new Random(0);
             //expected costs in Ms
             int totalMs = 0;
             //send 100 tasks (workload for tasks, is just some random sleep time that
             //the workers can perform, in real life each work would do more than sleep
             int upper  = 10;
             int height = 400;
             for (int lower = 0; lower < height; lower += 10)
             {
                 sender.SendFrame(lower + "," + upper + "," + height);
                 upper += 10;
             }
             Console.WriteLine("Total expected cost : {0} msec", totalMs);
             Console.WriteLine("Press Enter to quit");
             Console.ReadLine();
         }
 }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("====== VENTILATOR ======");

            using (var push = new PushSocket())
                using (var sink = new DealerSocket())
                {
                    push.Bind("tcp://127.0.0.1:8888");
                    sink.Connect("tcp://127.0.0.1:7777");

                    Console.WriteLine("Press enter when worker are ready");
                    Console.ReadLine();

                    Console.WriteLine("Sending start of batch to Sink");
                    sink.SendFrame("0");

                    Console.WriteLine("Sending tasks to workers");

                    var rnd     = new Random();
                    var totalMs = 0;

                    for (int taskNumber = 0; taskNumber < 100; taskNumber++)
                    {
                        int workload = rnd.Next(0, 100);
                        totalMs += workload;
                        Console.WriteLine("Workload : {0}", workload);
                        push.SendFrame(workload.ToString());
                    }

                    Console.WriteLine($"Total expected cost : {totalMs} msec");
                    Console.WriteLine("Press Enter to quit");
                    Console.ReadLine();
                }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            string connectionString = args[0];

            using (var send = new PushSocket(">tcp://127.0.0.1:9999"))
                using (var receive = new ResponseSocket(connectionString))
                {
                    while (true)
                    {
                        // Block for request
                        var message = receive.ReceiveFrameString();
                        var msgId   = Guid.NewGuid().ToString();

                        // Acknowledge
                        receive.SendFrame("200, ACK");

                        // Do Work ...
                        Thread.Sleep(2000);

                        // Send response
                        send.SendFrame(string.Format("Handler {0} completed task {1}",
                                                     connectionString, msgId));

                        // Exit handler
                        break;
                    }
                }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            Console.WriteLine("====== WORKER ======");

            var sinkPort       = ConfigurationManager.AppSettings.Get("sinkPort") ?? "8088";
            var ventilatorPort = ConfigurationManager.AppSettings.Get("ventilatorPort") ?? "400";

            using (var receiver = new PullSocket($">tcp://localhost:{sinkPort}"))
                using (var sender = new PushSocket($">tcp://localhost:{ventilatorPort}"))
                {
                    while (true)
                    {
                        string workload = receiver.ReceiveFrameString();

                        // the protocoll is as follows: [0] -> lower, [1] -> upper,  [2] -> height
                        string[] workLoadArray = workload.Split(',');

                        var calculator = new MandelbrotCalculator();
                        var result     = calculator.Calculate(Convert.ToInt32(workLoadArray[2]), 400, Convert.ToInt32(workLoadArray[0]), Convert.ToInt32(workLoadArray[1]));

                        byte[]          data;
                        BinaryFormatter binaryFormatter = new BinaryFormatter();

                        using (var memoryStream = new MemoryStream())
                        {
                            binaryFormatter.Serialize(memoryStream, result);
                            data = memoryStream.ToArray();
                        }

                        Console.WriteLine("Sending");
                        sender.SendFrame(data);
                    }
                }
        }
Ejemplo n.º 7
0
 private static void Main()
 {
     Console.WriteLine("Creating socket..");
     using (var pushSocket = new PushSocket(">tcp://localhost:5556")
     {
         /* So apparently this is needed to prevent the socket from being immediately disposed
          * after the last instruction of the using block.
          * With this setting, the socket shall be disposed only after the message has been sent.
          * This is equivalent to say "wait forever", but someone may arguably want to set a finite
          * amount of time when in production.
          */
         Options = { Linger = TimeSpan.FromSeconds(-1) }
     })
     {
         Console.WriteLine("Creating message..");
         var message = new Message
         {
             Text      = "test message",
             TimeStamp = DateTime.Now,
             Type      = "test",
             ValueCode = 0
         };
         Console.WriteLine("Serializing message..");
         using (var memoryStream = new MemoryStream())
         {
             var binaryFormatter = new BinaryFormatter();
             binaryFormatter.Serialize(memoryStream, message);
             var serializedMessage = memoryStream.ToArray();
             Console.WriteLine("Sending message..");
             pushSocket.SendFrame(serializedMessage);
         }
     }
     Console.WriteLine("Performing cleanup..");
     NetMQConfig.Cleanup();
 }
Ejemplo n.º 8
0
        public override void Publisher()
        {
            AsyncIO.ForceDotNet.Force();

            sender = new PushSocket();
            sender.Connect("tcp://" + IP + ":" + Port);
            Debug.Log("Connect ObjectSender to: " + "tcp://" + IP + ":" + Port);
            while (IsRunning)
            {
                Thread.Sleep(50);
                if (sendMessageQueue.Count > 3)
                {
                    sendMessageQueue.RemoveRange(0, sendMessageQueue.Count - 3);
                }
                if (sendMessageQueue.Count > 0)
                {
                    // Debug.Log("Send: " + sendMessageQueue[0]);

                    try
                    {
                        sender.SendFrame(sendMessageQueue[0], false); // true not wait
                        sendMessageQueue.RemoveAt(0);
                    }
                    catch { }
                }
            }

            // disconnectClose();
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            bool started = false;

            while (true)
            {
                if (started)
                {
                    Console.WriteLine("Please Press Enter to Stop...");
                    Console.ReadLine();
                    using (var server = new PushSocket())
                    {
                        server.Connect("tcp://127.0.0.1:5489");
                        server.SendFrame("false");
                        started = false;
                    }
                }
                else
                {
                    Console.WriteLine("Please Press Enter to Start...");
                    Console.ReadLine();
                    using (var send = new PushSocket())
                    {
                        send.Connect("tcp://127.0.0.1:5488");
                        send.SendFrame("true");
                        started = true;
                    }
                }
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            // Console.WriteLine("Connecting to hello world server…");
            // using (var requester = new RequestSocket())
            // {
            //     requester.Connect("tcp://localhost:5555");

            //     int requestNumber;
            //     for (requestNumber = 0; requestNumber != 100; requestNumber++)
            //     {
            //         Console.WriteLine("Sending Hello {0}...", requestNumber);
            //         requester.SendFrame("Hello");
            //         string str = requester.ReceiveFrameString();
            //         Console.WriteLine("Received World {0}", requestNumber);
            //     }
            // }
            using (var responder = new PushSocket())
            {
                responder.Bind("tcp://*:5555");

                while (true)
                {
                    //string str = responder.ReceiveFrameString();
                    string str = "hellllllo";
                    Console.WriteLine(str);
                    Thread.Sleep(50);  //  Do some 'work'
                    responder.SendFrame(str);
                }
            }
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            Console.WriteLine("====== VENTILATOR ======");


            Console.WriteLine("Press enter when all is set up");
            Console.ReadLine();

            using (var sender = new PushSocket("@tcp://*:80"))
            {
                Console.WriteLine("Sending tasks to workers");

                int step   = 10;
                int height = 200;  //400    hier kann height geändert werden
                int width  = 200;  //       hier kann width geändert werden
                for (int start = 0; start < height; start += 10)
                {
                    Thread.Sleep(100);
                    sender.SendFrame(start + "," + step + "," + width);
                    Console.WriteLine("asked for " + start + " to " + step);
                    step = step + 10;
                }

                Console.WriteLine("Press any key to quit");
                Console.ReadLine();
            }
        }
 public static void Main(string[] args)
 {
     // Task Worker
     // Connects PULL socket to tcp://localhost:5557
     // collects workload for socket from Ventilator via that socket
     // Connects PUSH socket to tcp://localhost:5558
     // Sends results to Sink via that socket
     Console.WriteLine("====== WORKER ======");
     using (var receiver = new PullSocket(">tcp://127.0.0.1:5557"))
         using (var sender = new PushSocket(">tcp://127.0.0.1:5558"))
         {
             //process tasks forever
             while (true)
             {
                 //workload from the vetilator is a simple delay
                 //to simulate some work being done, see
                 //Ventilator.csproj Proram.cs for the workload sent
                 //In real life some more meaningful work would be done
                 string workload = receiver.ReceiveFrameString();
                 //simulate some work being done
                 Thread.Sleep(int.Parse(workload));
                 //send results to sink, sink just needs to know worker
                 //is done, message content is not important, just the presence of
                 //a message means worker is done.
                 //See Sink.csproj Proram.cs
                 Console.WriteLine("Sending to Sink");
                 sender.SendFrame(string.Empty);
             }
         }
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("====== Back Queue STARTED ======");
            using var fromWorkerForPosion = new PullSocket($"@{ThreadSafeFactory.BackPosionQueue}");
            using var fromWorkerForUrl    = new PullSocket($"@{ThreadSafeFactory.BackUrlQueue}");
            using var forFrontForUrl      = new PushSocket($"@{ThreadSafeFactory.BackQueue}");
            Console.WriteLine("Socket initialized");

            var fromWorkerProcessorForFrontQueue = Task.Run(() =>
            {
                do
                {
                    try
                    {
                        Console.WriteLine($"Waiting for worker link");
                        var queueItem = fromWorkerForUrl.ReceiveFrameString();
                        Console.WriteLine($"Received [{queueItem}] from worker");
                        Console.WriteLine($"Sending to front queue");
                        forFrontForUrl.SendFrame(queueItem);
                        Console.WriteLine($"Sent to front queue");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error in Front Queue Processor {ex.Message}");
                    }
                } while (true);
            });
            var fromWorkerProcessorForPoison = Task.Run(() =>
            {
                do
                {
                    Console.WriteLine($"Waiting for poison items");
                    var workload = fromWorkerForPosion.ReceiveFrameString();
                    UrlPosionQueueItem queueItem = workload.FromJson <UrlPosionQueueItem>();
                    _posionQueue.Enqueue(queueItem);
                    Console.WriteLine($"Received poison [{queueItem.ToJson()}] from worker");
                } while (true);
            });

            var poisonQueueProcessor = Task.Run(() =>
            {
                do
                {
                    //while (_posionQueue.IsEmpty)
                    //{
                    //    Task.Delay(5000).Wait();
                    //}
                    if (_posionQueue.TryDequeue(out UrlPosionQueueItem queueItem))
                    {
                        Console.WriteLine($"Processing poison {queueItem.ToJson()}");
                    }
                    // TODO: Persist all posion queue items with failure reasons in db
                } while (true);
            });

            Task.WaitAll(fromWorkerProcessorForFrontQueue, /* fromWorkerProcessorForPoison,*/ poisonQueueProcessor);
            Console.WriteLine("====== FRONT QUEUE ======");
        }
        public void Test_Start_Should_Not_Fail_In_Case_Of_Processing_Exception()
        {
            using (AutoMock mock = AutoMock.GetLoose(this.output.Capture()))
            {
                IOptions <MessageHandlerOptions> options = Options.Create(new MessageHandlerOptions {
                    Address = "tcp://127.0.0.1:51861"
                });
                mock.Provide(options);

                mock.Mock <ITelegramService>()
                .SetupSequence(service => service.SendMessageAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
                .Throws(new Exception("Something threw an exception"))
                .Returns(Task.CompletedTask);

                using (var pushSocket = new PushSocket($"@{options.Value.Address}"))
                    using (var handler = mock.Create <MessageHandlerImpl>())
                    {
                        handler.Start();

                        pushSocket.SendFrame("some-message1");
                        pushSocket.SendFrame("some-message2");

                        Mock <ITelegramService> telegramService = mock.Mock <ITelegramService>();
                        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
                        Predicate <CancellationToken> isNotCancelled = token => !token.IsCancellationRequested;
                        while (!cts.Token.IsCancellationRequested)
                        {
                            try
                            {
                                telegramService.Verify(p => p.SendMessageAsync("some-message1", Match.Create(isNotCancelled)), Times.Once);
                                telegramService.Verify(p => p.SendMessageAsync("some-message2", Match.Create(isNotCancelled)), Times.Once);
                                break;
                            }
                            catch (MockException)
                            {
                                if (cts.Token.IsCancellationRequested)
                                {
                                    throw;
                                }
                            }
                        }
                    }
            }
        }
Ejemplo n.º 15
0
        protected override void Produce(PushSocket socket, int messageSize)
        {
            var msg = new byte[messageSize];

            msg[messageSize / 2] = 0x42;

            for (int i = 0; i < MsgCount; i++)
            {
                socket.SendFrame(msg);
            }
        }
Ejemplo n.º 16
0
        public void SimplePushPull()
        {
            using (var pullSocket = new PullSocket())
                using (var pushSocket = new PushSocket())
                {
                    var port = pullSocket.BindRandomPort("tcp://127.0.0.1");
                    pushSocket.Connect("tcp://127.0.0.1:" + port);

                    pushSocket.SendFrame("hello");

                    Assert.AreEqual("hello", pullSocket.ReceiveFrameString());
                }
        }
Ejemplo n.º 17
0
        public void EmptyMessage()
        {
            using (var pullSocket = new PullSocket())
                using (var pushSocket = new PushSocket())
                {
                    var port = pullSocket.BindRandomPort("tcp://127.0.0.1");
                    pushSocket.Connect("tcp://127.0.0.1:" + port);

                    pushSocket.SendFrame(new byte[300]);

                    Assert.AreEqual(300, pullSocket.ReceiveFrameString().Length);
                }
        }
Ejemplo n.º 18
0
        void StartClient()
        {
            Debug.Log("Client is On!!");
            using (var pushSocket = new PushSocket())
                using (var subscriberSocket = new SubscriberSocket())
                {
                    pushSocket.Connect("tcp://localhost:20002");
                    subscriberSocket.Connect("tcp://localhost:20001");
                    subscriberSocket.Subscribe("topicA");

                    Thread.Sleep(TimeSpan.FromSeconds(2));

                    Debug.Log("Send !!");
                    pushSocket.SendFrame("Hello Server First!");
                    while (true)
                    {
                        string str = subscriberSocket.ReceiveFrameString();
                        Debug.Log("[Client] Get! :: " + str);
                        pushSocket.SendFrame("Hello Server!");
                        Debug.Log("[Client] Send Hello Server!");
                    }
                }
        }
        public void Notify(ExposedService exposedService)
        {
            Log.Logger.ForContext <MessageQueueNotificationService>().Information("New container event: {@ExposedService}", exposedService);
            var frame = GetSerializedMessageFrame(exposedService);

            try
            {
                _pushSocket.SendFrame(frame);
            }
            catch (Exception exception)
            {
                Log.Logger.ForContext <MessageQueueNotificationService>().Error(exception, "Error while sending exposed service change to the message queue.");
            }
        }
Ejemplo n.º 20
0
        public void Start()
        {
            Task.Run(() =>
            {
                using (var receiver = new PullSocket(Endpoint))
                {
                    while (true)
                    {
                        var command = receiver.ReceiveFrameBytes();

                        var msg = JsonConvert.DeserializeObject <Message>(Encoding.UTF32.GetString(command));

                        switch (msg.Subject)
                        {
                        case NetMQPeerDirectory.Ack:
                            TestsNetMQContext.Increment();
                            break;

                        case NetMQPeerDirectory.Command:
                            TestsNetMQContext.Increment();
                            break;

                        case NetMQPeerDirectory.Event:
                            TestsNetMQContext.Increment();
                            break;
                        }
                    }
                }
            }, _token);


            Task.Run(async() =>
            {
                using (var sender = new PushSocket($"{DirectoryEndpoint}"))
                {
                    var message = new Message()
                    {
                        Endpoint = Endpoint,
                        Subject  = NetMQPeerDirectory.RegisterCommand
                    };

                    var msg = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(message));

                    sender.SendFrame(msg);

                    await Task.Delay(100);
                }
            });
        }
Ejemplo n.º 21
0
        public static void Main(string[] args)
        {
            Console.WriteLine("====== WORKER ======");
            using (var receiver = new PullSocket(">tcp://localhost:80"))
                using (var sender = new PushSocket(">tcp://localhost:400"))
                {
                    //process tasks forever
                    while (true)
                    {
                        string workload = receiver.ReceiveFrameString();
                        Console.WriteLine("got");
                        string[] values = workload.Split(',');

                        double xReminder = -2 + ((double)Int32.Parse(values[0]) * 0.013);

                        MandlBrotCalcer calcer = new MandlBrotCalcer();

                        List <(int, int, int)> list = calcer.CalcPart(Int32.Parse(values[0]), Int32.Parse(values[1]), 0, Int32.Parse(values[2]), 18, 4, xReminder, 1.2, 0.013);

                        BinaryFormatter binaryFormatter = new BinaryFormatter();

                        byte[] listBytes;

                        using (var memoryStream = new MemoryStream())
                        {
                            binaryFormatter.Serialize(memoryStream, list);
                            listBytes = memoryStream.ToArray();
                        }

                        sender.SendFrame(listBytes);

                        Console.WriteLine("Sending to Sink");
                        sender.SendFrame(string.Empty);
                    }
                }
        }
Ejemplo n.º 22
0
        //helper functions
        #region helper functions
        static public byte[] Communicate(string request)
        {
            lock (commsLock) {
                Console.WriteLine($"Sending {request}");
                sender.SendFrame(request);

                //server.ReceiveFrameString();
                var message = responseReceiver.ReceiveFrameBytes();

                if (message.Length == 0)
                {
                    throw new Exception("empty response");
                }

                return(message);
            }
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            var database = new Database();

            using (var priceValidator = new SubscriberSocket(">tcp://localhost:10000"))
                using (var productPush = new PushSocket("@tcp://*:12000"))
                {
                    priceValidator.Subscribe("product");
                    while (true)
                    {
                        var topic = priceValidator.ReceiveFrameString();
                        var productTohavePriceValidated = priceValidator.ReceiveFrameString();
                        var product = Newtonsoft.Json.JsonConvert.DeserializeObject <Product>(productTohavePriceValidated);
                        Console.WriteLine(productTohavePriceValidated);

                        var databaseProduct             = database.Products.SingleOrDefault(x => x.Id == product.Id);
                        ValidatedProductMessage message = null;

                        if (databaseProduct != null)
                        {
                            if (string.IsNullOrEmpty(product.Name))
                            {
                                message = new ValidatedProductMessage(product, "Product name is required, can not be displayed on the site.");
                            }
                            else if (string.IsNullOrEmpty(product.Description))
                            {
                                message = new ValidatedProductMessage(product, "Product description is required, can not be displayed on the site.");
                            }
                            else if (product.Price > 1000 && product.RelatedProducts.Count == 0)
                            {
                                message = new ValidatedProductMessage(product, "Expensive products must to have at least 1 related product, can not be displayed on the site.");
                            }
                            else
                            {
                                message = new ValidatedProductMessage(product);
                            }
                        }
                        else
                        {
                            message = new ValidatedProductMessage(null, "Product not found, need to be created by the Product Team before be published on site");
                        }

                        productPush.SendFrame(Newtonsoft.Json.JsonConvert.SerializeObject(message));
                    }
                }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            // Task Worker
            // Connects PULL socket to tcp://localhost:5557
            // collects workload for socket from Ventilator via that socket
            // Connects PUSH socket to tcp://localhost:5558
            // Sends results to Sink via that socket
            Console.WriteLine("====== WORKER ======");

            var mainServer = ConfigurationManager.AppSettings.Get("mainServer");

            using (var receiver = new PullSocket(">tcp://localhost:80"))
                using (var sender = new PushSocket(">tcp://localhost:400"))
                {
                    //process tasks forever
                    while (true)
                    {
                        //workload from the vetilator is a simple delay
                        //to simulate some work being done, see
                        //Ventilator.csproj Proram.cs for the workload sent
                        //In real life some more meaningful work would be done
                        string workload = receiver.ReceiveFrameString();

                        //0 ... lower, 1... upper... 2..height
                        string[] workLoadArray = workload.Split(',');

                        var calculator = new Calculator();

                        var result = calculator.Calculate(Convert.ToInt32(workLoadArray[0]), Convert.ToInt32(workLoadArray[1]), Convert.ToInt32(workLoadArray[2]), 400);


                        byte[]          dataGame;
                        BinaryFormatter binaryFormatter = new BinaryFormatter();

                        using (var memoryStream = new MemoryStream())
                        {
                            binaryFormatter.Serialize(memoryStream, result);
                            dataGame = memoryStream.ToArray();
                        }

                        Console.WriteLine("Sending to Sink");
                        sender.SendFrame(dataGame);
                    }
                }
        }
Ejemplo n.º 25
0
        private void FanOutEntry(object n)
        {
            FanoutRun f;
            string    name = (string)n;

            if (FanoutRM.ContainsKey(name))
            {
                f = FanoutRM[name];
            }
            else
            {
                Logging.logger.Error("FanOutEntry get name failed " + name);
                return;
            }

            PushSocket p = new PushSocket();
            string     e = "tcp://" + f.point.ip + ":" + f.point.port;

            try
            {
                p.Bind(e);
                f.pushsock = p;
            }
            catch (Exception err)
            {
                Logging.logger.Error(ModName + " bind funin socket failed " + e + " " + err.Message);
                throw (err);
            }

            string str;

            f.Working = true;
            while (f.Running)
            {
                str = Entry4GetFanoutData(f.name);
                if (str != null)
                {
                    p.SendFrame(str);
                }
                DelayTime();
            }
            f.Working = false;
            p.Close();
            return;
        }
 public bool Send(string message, string serverPushAddress, int serverPushPort)
 {
     try
     {
         using (var producer = new PushSocket())
         {
             producer.Connect(serverPushAddress + ":" + serverPushPort);
             producer.SendFrame(message);
             System.Threading.Thread.Sleep(2000);
             producer.Disconnect(serverPushAddress + ":" + serverPushPort);
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 27
0
        public async Task StartPushing()
        {
            var message = string.Format("Id = {0}", _id);
            var bytes   = Encoding.ASCII.GetBytes(message);

            while (true)
            {
                socket.SendFrame(message);
                Console.WriteLine(" {0} Sent message", _id);
                //await Task.Delay(_id * 10);

                string fromServerMessage = socket.ReceiveFrameString();
                Console.WriteLine("Client {0} From Server: {1}", _id, fromServerMessage);
                if (!fromServerMessage.Contains(_id.ToString()))
                {
                    throw new InvalidOperationException(string.Format("{0} Received {1}", _id, fromServerMessage));
                }
            }
        }
Ejemplo n.º 28
0
        public void create(int antal)
        {
            Message m = new Message();

            //var pubSocket = new PublisherSocket();
            using (var sender = new PushSocket("@tcp://*:5556"))
            {
                Console.WriteLine("Publisher started");
                //pubSocket.Options.SendHighWatermark = 10000;
                //pubSocket.Bind("tcp://*:5556");
                //Thread.Sleep(100);
                for (var i = 0; i < antal; i++)
                {
                    //Console.WriteLine("Sending message : {0}", msg);
                    sender.SendFrame(m.Navn);
                    //Thread.Sleep(100);
                }
            }
            Console.WriteLine(antal + " Beskeder sendt");
        }
Ejemplo n.º 29
0
    // Overide the run thread
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (PushSocket client = new PushSocket())
        {
            string addr = "tcp://localhost:" + port;
            client.Connect(addr);
            while (Running)
            {
                if (newDataFlag)
                {
                    //Debug.Log("ZMQPusher-> Data Sent through ZMQ.");
                    client.SendFrame(sendData);
                    newDataFlag = false;
                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }
Ejemplo n.º 30
0
        public void CloseSendingSockets()
        {
            Console.WriteLine("FINISHED SENDING DATA");
            var selfSocket = new PushSocket();

            selfSocket.Connect("tcp://" + RemoteServGr.NodeAddress);
            var msg = new Message
            {
                MsgType       = MessageType.EndingProgram,
                SendingServer = RemoteServGr.NodeAddress
            };
            var msgJson = JsonConvert.SerializeObject(msg);

            selfSocket.SendFrame(msgJson);

            foreach (var socket in RemoteServGr.RemoteServerSockets)
            {
                socket.Value.Close();
            }
            selfSocket.Close();
        }
Ejemplo n.º 31
0
        public void Run()
        {
            Console.WriteLine("[CLIENT {0}] Starting", m_id);

            var rnd = new Random(m_id);
            // each request shall have an unique id in order to recognize an reply for a request
            var messageId = new byte[5];
            // create clientId for messages
            var clientId = new[] { m_id };
            // a flag to signal that an answer has arrived
            bool messageAnswered = false;
            // we use a poller because we have a socket and a timer to monitor
            using (var clientPoller = new NetMQPoller())
            using (var client = new RequestSocket())
            using (var monitor = new PushSocket())
            {
                client.Connect(m_localFrontendAddress);
                monitor.Connect(m_monitorAddress);

                client.Options.Identity = new[] { m_id };
                var timer = new NetMQTimer((int)TimeSpan.FromSeconds(10).TotalMilliseconds);

                // use as flag to indicate exit
                var exit = false;

                // every 10 s check if message has been received, if not then send error message and ext
                // and restart timer otherwise
                timer.Elapsed += (s, e) =>
                {
                    if (messageAnswered)
                    {
                        e.Timer.Enable = true;
                    }
                    else
                    {
                        var msg = string.Format("[CLIENT {0}] ERR - EXIT - lost message {1}", m_id, messageId);
                        // send an error message
                        monitor.SendFrame(msg);

                        // if poller is started than stop it
                        if (clientPoller.IsRunning)
                            clientPoller.Stop();
                        // mark the required exit
                        exit = true;
                    }
                };

                // process arriving answers
                client.ReceiveReady += (s, e) =>
                {
                    // mark the arrival of an answer
                    messageAnswered = true;
                    // worker is supposed to answer with our request id
                    var reply = e.Socket.ReceiveMultipartMessage();

                    if (reply.FrameCount == 0)
                    {
                        // something went wrong
                        monitor.SendFrame(string.Format("[CLIENT {0}] Received an empty message!", m_id));
                        // mark the exit flag to ensure the exit
                        exit = true;
                    }
                    else
                    {
                        var sb = new StringBuilder();

                        // create success message
                        foreach (var frame in reply)
                            sb.Append("[" + frame.ConvertToString() + "]");

                        // send the success message
                        monitor.SendFrame(string.Format("[CLIENT {0}] Received answer {1}",
                            m_id,
                            sb.ToString()));
                    }
                };

                // add socket & timer to poller
                clientPoller.Add(client);
                clientPoller.Add(timer);

                // start poller in another thread to allow the continued processing
                clientPoller.RunAsync();

                // if true the message has been answered
                // the 0th message is always answered
                messageAnswered = true;

                while (!exit)
                {
                    // simulate sporadic activity by randomly delaying
                    Thread.Sleep((int)TimeSpan.FromSeconds(rnd.Next(5)).TotalMilliseconds);

                    // only send next message if the previous one has been replied to
                    if (messageAnswered)
                    {
                        // generate random 5 byte as identity for for the message
                        rnd.NextBytes(messageId);

                        messageAnswered = false;

                        // create message [client adr][empty][message id] and send it
                        var msg = new NetMQMessage();

                        msg.Push(messageId);
                        msg.Push(NetMQFrame.Empty);
                        msg.Push(clientId);

                        client.SendMultipartMessage(msg);
                    }
                }

                // stop poller if needed
                if (clientPoller.IsRunning)
                    clientPoller.Stop();
            }
        }