Example #1
0
        static void Main(string[] args)
        {
            try
            {
                options = new Options();
                var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
                if (!parser.ParseArguments(args, options))
                    Environment.Exit(1);

                using (var ctx = ZmqContext.Create())
                {
                    var pubSocket = ctx.CreateSocket(SocketType.PUB);
                    pubSocket.Bind(options.pubEndpoint);
                    pubSocket.SendReady +=new EventHandler<SocketEventArgs>(pubSocket_SendReady);
                    var repSocket = ctx.CreateSocket(SocketType.REP);
                    repSocket.Bind(options.repEndpoint);
                    repSocket.SendReady +=new EventHandler<SocketEventArgs>(repSocket_SendReady);
                    repSocket.ReceiveReady +=new EventHandler<SocketEventArgs>(repSocket_ReceiveReady);
                    Poller poller = new Poller(new ZmqSocket[] {pubSocket, repSocket});
                    while (true)
                    {
                        poller.Poll();
                        if (options.maxMessage >= 0)
                            if (msgCptr > options.maxMessage)
                                Environment.Exit(0);
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
Example #2
0
        //  ---------------------------------------------------------------------
        //  This is our client task
        //  It connects to the server, and then sends a request once per second
        //  It collects responses as they arrive, and it prints them out. We will
        //  run several client tasks in parallel, each with a different random ID.
        public static void ClientTask()
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket client = context.CreateSocket(SocketType.DEALER))
                {
                    //  Generate printable identity for the client
                    ZHelpers.SetID(client, Encoding.Unicode);
                    string identity = Encoding.Unicode.GetString(client.Identity);
                    client.Connect("tcp://localhost:5570");

                    client.ReceiveReady += (s, e) =>
                    {
                        var zmsg = new ZMessage(e.Socket);
                        Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString());
                    };

                    int requestNumber = 0;

                    var poller = new Poller(new List<ZmqSocket> { client });

                    while (true)
                    {
                        //  Tick once per second, pulling in arriving messages
                        for (int centitick = 0; centitick < 100; centitick++)
                        {
                            poller.Poll(TimeSpan.FromMilliseconds(10000));
                        }
                        var zmsg = new ZMessage("");
                        zmsg.StringToBody(String.Format("request: {0}", ++requestNumber));
                        zmsg.Send(client);
                    }
                }
            }
        }
        public void Run()
        {
            using (ZmqSocket ventilator = _context.CreateSocket(SocketType.PULL),
                sink = _context.CreateSocket(SocketType.PUSH),
                controller = _context.CreateSocket(SocketType.SUB))
            {
                ventilator.Connect("inproc://ventilator");
                sink.Connect("inproc://sink");

                SetupController(controller);

                _work = true;

                ventilator.ReceiveReady += (socket, events) =>
                    {
                        RecieverPollInHandler(ventilator, sink);
                    };

                var poller = new Poller(new[] {ventilator, controller});

                while (_work)
                {
                    poller.Poll();
                }

            }
        }
        private void start(CancellationToken token, TaskCompletionSource<bool> flag)
        {
            Console.WriteLine("starting proxy...");
            using (var router = _context.CreateSocket(SocketType.ROUTER))
            using (var dealer = _context.CreateSocket(SocketType.DEALER))
            {
                router.Bind("tcp://127.0.0.1:8085");
                dealer.Bind("tcp://127.0.0.1:8087");

                Console.WriteLine("Binding done...");
                router.ReceiveReady += (sender, args) => proxy(router, dealer);
                dealer.ReceiveReady += (sender, args) => proxy(dealer, router);
                var poller = new Poller(new[] {router, dealer});
                Console.WriteLine("poll");

                flag.SetResult(true);

                //If you were following along with the live coding, this is the bit that was wrong.
                //I forgot the "== false" part. Kinda important, huh? Who'd have thunk ;P
                while (token.IsCancellationRequested == false)
                {
                    poller.Poll(TimeSpan.FromMilliseconds(500));
                }

                Console.WriteLine("Exiting...");
                poller.Dispose();
                Console.WriteLine("Poller disposed...");
            }

            Console.WriteLine("Poller sockets disposed...");
        }
Example #5
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), sender = context.CreateSocket(SocketType.PUSH), controller = context.CreateSocket(SocketType.SUB))
                {
                    receiver.Connect("tcp://localhost:5557");
                    sender.Connect("tcp://localhost:5558");
                    controller.Connect("tcp://localhost:5559");
                    controller.SubscribeAll();

                    bool run = true;

                    var poller = new Poller(new List<ZmqSocket> { receiver, controller });

                    receiver.ReceiveReady += (s, e) => ReceiverPollInHandler(e.Socket, sender);
                    controller.ReceiveReady += delegate { run = false; };

                    //  Process tasks as long as the controller does not signal the end.
                    while (run)
                    {
                        poller.Poll();
                    }
                }
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.ROUTER))
                {
                    frontend.Bind("tcp://*:5555"); // For Clients
                    backend.Bind("tcp://*:5556"); // For Workers

                    //  Logic of LRU loop
                    //  - Poll backend always, frontend only if 1+ worker ready
                    //  - If worker replies, queue worker as ready and forward reply
                    //    to client if necessary
                    //  - If client requests, pop next worker and send request to it

                    //  Queue of available workers
                    var workerQueue = new Queue<byte[]>();

                    //  Handle worker activity on backend
                    backend.ReceiveReady += (s, e) =>
                                                 {
                                                     var zmsg = new ZMessage(e.Socket);
                                                     //  Use worker address for LRU routing
                                                     workerQueue.Enqueue(zmsg.Unwrap());

                                                     //  Forward message to client if it's not a READY
                                                     if (!Encoding.Unicode.GetString(zmsg.Address).Equals(LRU_READY))
                                                     {
                                                         zmsg.Send(frontend);
                                                     }
                                                 };

                    frontend.ReceiveReady += (s, e) =>
                                                  {
                                                      //  Now get next client request, route to next worker
                                                      //  Dequeue and drop the next worker address
                                                      var zmsg = new ZMessage(e.Socket);
                                                      zmsg.Wrap(workerQueue.Dequeue(), new byte[0]);
                                                      zmsg.Send(backend);
                                                  };

                    var poller = new Poller(new ZmqSocket[] { frontend, backend });

                    while (true)
                    {
                        //int rc = ZmqContext.Poller(workerQueue.Count > 0
                        //                            ? new List<ZmqSocket>(new ZmqSocket[] {frontend, backend})
                        //                            : new List<ZmqSocket>(new ZmqSocket[] {backend}));

                        int rc = poller.Poll();

                        if (rc == -1)
                        {
                            break;
                        }
                    }
                }
            }
        }
Example #7
0
        //  ---------------------------------------------------------------------
        //  This is our client task
        //  It connects to the server, and then sends a request once per second
        //  It collects responses as they arrive, and it prints them out. We will
        //  run several client tasks in parallel, each with a different random ID.
        public static void ClientTask()
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket client = context.CreateSocket(SocketType.DEALER))
                {
                    //  Generate printable identity for the client
                    string identity = ZHelpers.SetID(client, Encoding.Unicode);
                    //client.Connect("tcp://localhost:5570");
                    string serviceRepoAddress = ConfigurationSettings.AppSettings["serviceRepoAddressZMQ"];
                    client.Connect(serviceRepoAddress);

                    client.ReceiveReady += (s, e) =>
                    {
                        var zmsg = new ZMessage(e.Socket);
                        Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString());
                    };

                    int requestNumber = 0;

                    var poller = new Poller(new List<ZmqSocket> { client });

                    var zmsg2 = new ZMessage("");

                    JSONMessage jsonMess = new JSONMessage();
                    jsonMess.Service = "Klient";
                    jsonMess.Function = "RegisterService";
                    jsonMess.Parameters = new string[] { "Klient", "Location", "binding" };
                    string json = JsonConvert.SerializeObject(jsonMess);
                    zmsg2.StringToBody(json);
                    zmsg2.Send(client);

                    while (true)
                    {
                        //  Tick once per second, pulling in arriving messages
                        for (int centitick = 0; centitick < 100; centitick++)
                        {
                            poller.Poll(TimeSpan.FromMilliseconds(10));
                        }

                        var zmsg = new ZMessage("");

                        jsonMess = new JSONMessage();
                        jsonMess.Service = "Klient";
                        jsonMess.Function = "GetServiceLocation";
                        jsonMess.Parameters = new string[] { "Klient", "binding" };
                        json = JsonConvert.SerializeObject(jsonMess);
                        zmsg.StringToBody(json);
                        zmsg.Send(client);
                    }
                }
            }
        }
Example #8
0
        public static void Main(string[] args)
        {
            var randomizer = new Random(DateTime.Now.Millisecond);

            if (args.Length < 2)
            {
                Console.WriteLine("Usage: peering1 <myself> <peer_1> ... <peer_N>");
                return;
            }

            var myself = args[0];
            Console.WriteLine("Hello, I am " + myself);

            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket statebe = context.CreateSocket(SocketType.PUB), statefe = context.CreateSocket(SocketType.SUB))
                {
                    var bindAddress = "tcp://127.0.0.1:" + myself;
                    statebe.Bind(bindAddress);
                    Thread.Sleep(1000);

                    for (int arg = 1; arg < args.Length; arg++)
                    {
                        var endpoint = "tcp://127.0.0.1:" + args[arg];
                        statefe.Connect(endpoint);
                        statefe.Subscribe(Encoding.Unicode.GetBytes(string.Empty));
                        Thread.Sleep(1000);
                    }

                    statefe.ReceiveReady += (s, e) =>
                                                 {
                                                     string peerName = e.Socket.Receive(Encoding.Unicode);
                                                     string available = e.Socket.Receive(Encoding.Unicode);

                                                     Console.WriteLine("{0} - {1} workers free\n", peerName, available);
                                                 };

                    var poller = new Poller(new List<ZmqSocket> { statefe });

                    while (true)
                    {
                        int count = poller.Poll(TimeSpan.FromMilliseconds(1000 * 1000));
                        
                        if (count == 0)
                        {
                            statebe.Send(myself, Encoding.Unicode);
                            statebe.Send(randomizer.Next(10).ToString(), Encoding.Unicode);
                        }
                    }
                }
            }
        }
Example #9
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.DEALER))
                {
                    frontend.Bind("tcp://*:5559");
                    backend.Bind("tcp://*:5560");

                    frontend.ReceiveReady += (sender, e) => FrontendPollInHandler(e.Socket, backend);
                    backend.ReceiveReady += (sender, e) => BackendPollInHandler(e.Socket, backend);

                    var poller = new Poller(new List<ZmqSocket> { frontend, backend });

                    while (true)
                    {
                        poller.Poll();
                    }
                }
            }
        }
Example #10
0
        public void Process() {
            //  Socket to receive messages on
            receiver.Connect("tcp://localhost:5557");
            //  Socket to send messages to
            sender.Connect("tcp://localhost:5558");
            //  Socket for control input
            controller.Connect("tcp://localhost:5559");
            controller.Subscribe(Encoding.Unicode.GetBytes(string.Empty));

            //  Process messages from receiver and controller
            receiver.ReceiveReady += ReceiverPollInHandler;
            controller.ReceiveReady += ControllerPollInHandler;

            var poller = new Poller(new List<ZmqSocket> { receiver, controller });

            //  Process messages from both sockets
            killCommand = false;
            while (!killCommand) {
                poller.Poll();
            }
        }
Example #11
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                var client = CreateServerSocket(context);

                while (retriesLeft > 0)
                {
                    sequence++;
                    Console.WriteLine("Sending ({0})", sequence);
                    client.Send(sequence.ToString(), Encoding.Unicode);
                    expectReply = true;

                    while (expectReply)
                    {
                        var poller = new Poller(new List<ZmqSocket> { client });
                        int count = poller.Poll(TimeSpan.FromMilliseconds(requestTimeout * 1000));

                        if (count == 0)
                        {
                            retriesLeft--;

                            if (retriesLeft == 0)
                            {
                                Console.WriteLine("Server seems to be offline, abandoning");
                                break;
                            }
                            else
                            {
                                Console.WriteLine("No response from server, retrying..");

                                client = null;
                                client = CreateServerSocket(context);
                                client.Send(sequence.ToString(), Encoding.Unicode);
                            }
                        }
                    }
                }
            }
        }
Example #12
0
        private void start(ZmqContext ctx, TaskCompletionSource<bool> ready)
        {
            using(var router = ctx.CreateSocket(SocketType.ROUTER))
            using (var dealer = ctx.CreateSocket(SocketType.DEALER))
            {
                router.Bind(Endpoints.InProcFront);
                dealer.Bind(Endpoints.InProcBack);

                router.ReceiveReady += (s, e) => relay(router, dealer);
                dealer.ReceiveReady += (s, e) => relay(dealer, router);

                var poller = new Poller(new[] {router, dealer});
                ready.SetResult(true);

                while (_token.IsCancellationRequested == false)
                {
                    poller.Poll(TimeSpan.FromMilliseconds(100));
                }

                poller.Dispose(); ;
            }
        }
Example #13
0
        // This is half synchronous, half asynchronous - we can use timers for the heartbeating and probably some more nice stuff
        public void Mediate()
        {
            ZmqContext.DefaultEncoding = Encoding.UTF8;
            using (var context = ZmqContext.Create())
            {
                var socket = context.CreateSocket(SocketType.ROUTER);
                socket.Linger = new TimeSpan(HeartbeatInterval * TimeSpan.TicksPerMillisecond);
                this._socket = socket;

                this._socket.Bind(this.addr);

                this._socket.ReceiveReady += this.HandleMessages;
                var poller = new Poller(new List<ZmqSocket>() { this._socket });

                while (Thread.CurrentThread.IsAlive)
                {
                    poller.Poll(new TimeSpan(HeartbeatInterval/100*TimeSpan.TicksPerMillisecond));
                    this.PurgeWorkers();
                    this.SendHeartbeats();
                }
                socket.Close();
            }
        }
Example #14
0
        public void Start(Options options)
        {
            using(var context = ZmqContext.Create())
            using(var frontend = context.CreateSocket(SocketType.ROUTER))
            using(var backend = context.CreateSocket(SocketType.ROUTER))
            using(var poller = new Poller(new[]{frontend,backend}))
            {
                var frontendEndpoint = string.Format ("tcp://{0}", options.SocketFrontEnd);
                Console.WriteLine ("Front-end socket binding to: {0}", frontendEndpoint);
                frontend.Bind(frontendEndpoint);
                frontend.ReceiveReady += FrontEndReady;

                var backendEndpoint = string.Format ("tcp://{0}", options.SocketBackEnd);
                Console.WriteLine ("Back-end socket connecting to: {0}", backendEndpoint);
                backend.Connect(backendEndpoint);
                backend.ReceiveReady += BackEndReady;

                while (true)
                {
                    poller.Poll();
                }

            }
        }
Example #15
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                //  Connect to task ventilator and weather server
                using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), subscriber = context.CreateSocket(SocketType.SUB))
                {
                    receiver.Connect("tcp://localhost:5557");
                    subscriber.Connect("tcp://localhost:5556");
                    subscriber.Subscribe(Encoding.Unicode.GetBytes("10001 "));

                    receiver.ReceiveReady += ReceiverPollInHandler;
                    subscriber.ReceiveReady += SubscriberPollInHandler;

                    var poller = new Poller(new List<ZmqSocket> {  });
                    
                    //  Process messages from both sockets
                    while (true)
                    {
                        poller.Poll();
                    }
                }
            }
        }
Example #16
0
        private static void Open(Object cancelationToken)
        {
            context = ZmqContext.Create();

            frontend = context.CreateSocket(SocketType.ROUTER);
            backend = context.CreateSocket(SocketType.DEALER);
            backend.Identity = Encoding.UTF8.GetBytes("inproc://workers");
            frontend.Bind("tcp://127.0.0.1:5000");

            backend.Bind("inproc://workers");

            workerThreads = new Thread[2];
            for (int threadId = 0; threadId < workerThreads.Length; threadId++)
            {
                workerThreads[threadId] = new Thread(WorkerRoutine);
                workerThreads[threadId].Start(context);
            }

            frontend.ReceiveReady += new EventHandler<SocketEventArgs>(frontend_ReceiveReady);
            backend.ReceiveReady += new EventHandler<SocketEventArgs>(backend_ReceiveReady);

            Poller poller = new Poller(new[] { frontend, backend });
            var token = (CancellationToken)cancelationToken;
            while (!token.IsCancellationRequested)
            {
                poller.Poll(TimeSpan.FromMilliseconds(100));
            }
        }
Example #17
0
        private static void WorkerRoutine(object context)
        {
            ZmqSocket receiver = ((ZmqContext)context).CreateSocket(SocketType.REP);
            receiver.Connect("inproc://workers");
            receiver.ReceiveReady += new EventHandler<SocketEventArgs>(worker_ReceiveReady);
            Poller poller = new Poller(new[] { receiver });

            while (!cancellationTokenSource.Token.IsCancellationRequested)
            {
                poller.Poll(TimeSpan.FromMilliseconds(100));
            }
        }
Example #18
0
        private static void WorkerRoutine(object context)
        {
            ZmqSocket receiver = ((ZmqContext)context).CreateSocket(SocketType.DEALER);
            ZmqSocket sender = ((ZmqContext)context).CreateSocket(SocketType.DEALER);

            receiver.Connect(workersEndpoint);
            sender.Connect("tcp://127.0.0.1:5000");

            receiver.ReceiveReady += new EventHandler<SocketEventArgs>(
                (s, e) =>
                {
                    ZmqMessage message = e.Socket.ReceiveMessage();
                    Console.WriteLine("[worker] Received {0} bytes {1} frames", message.TotalSize, message.FrameCount);
                    sender.SendMessage(message);
                }
                );

            sender.ReceiveReady += new EventHandler<SocketEventArgs>(
                (s, e) =>
                {
                    ZmqMessage message = e.Socket.ReceiveMessage();
                    Console.WriteLine("[sender] Received {0} bytes {1} frames", message.TotalSize, message.FrameCount);
                    receiver.SendMessage(message);
                });

            Poller poller = new Poller(new[] { receiver, sender });

            while (!cancellationTokenSource.Token.IsCancellationRequested)
            {
                poller.Poll(TimeSpan.FromMilliseconds(100));
            }
            receiver.Dispose();
            sender.Dispose();
        }
Example #19
0
        /// <summary>
        /// Receives new requests by polling, and sends data when it has arrived
        /// </summary>
        private void Server()
        {
            var timeout = TimeSpan.FromMilliseconds(10);
            _routerSocket.ReceiveReady += socket_ReceiveReady;
            KeyValuePair<HistoricalDataRequest, List<OHLCBar>> newDataItem;
            var ms = new MemoryStream();

            using (var poller = new Poller(new[] { _routerSocket }))
            {
                while (_runServer)
                {
                    poller.Poll(timeout); //this'll trigger the ReceiveReady event when we've got an incoming request

                    //check if there's anything in the queue, if there is we want to send it
                    if (_dataQueue.TryDequeue(out newDataItem))
                    {
                        //this is a 5 part message
                        //1st message part: the identity string of the client that we're routing the data to
                        string clientIdentity = newDataItem.Key.RequesterIdentity;

                        _routerSocket.SendMore(clientIdentity, Encoding.UTF8);

                        //2nd message part: the type of reply we're sending
                        _routerSocket.SendMore("HISTREQREP", Encoding.UTF8);

                        //3rd message part: the HistoricalDataRequest object that was used to make the request
                        _routerSocket.SendMore(MyUtils.ProtoBufSerialize(newDataItem.Key, ms)); //TODO make sure that the original request is returned

                        //4th message part: the size of the uncompressed, serialized data. Necessary for decompression on the client end.
                        byte[] uncompressed = MyUtils.ProtoBufSerialize(newDataItem.Value, ms);
                        _routerSocket.SendMore(BitConverter.GetBytes(uncompressed.Length));

                        //5th message part: the compressed serialized data.
                        byte[] compressed = LZ4Codec.EncodeHC(uncompressed, 0, uncompressed.Length); //compress
                        _routerSocket.Send(compressed);
                    }
                }
            }

            ms.Dispose();
            _routerSocket.Dispose();
            _context.Dispose();
            ServerRunning = false;
        }
Example #20
0
        /// <summary>
        ///     Will send a passed message to whatever endpoint is defined, with whatever service is defined.
        /// </summary>
        /// <param name="msg">a queue of byte arrays, containing the request body as defined in the Majordomo Protocol</param>
        public virtual String SendReceiveString(List<byte[]> msg)
        {
            var outp = MDP.Client.Request(this.Service, msg);
            outp.Prepend(new[] {new byte[0]});

            String message = String.Empty;

            Socket.ReceiveReady += (sender, args) =>
            {
                var m = args.Socket.ReceiveMessage();
                var origin = m.Unwrap();

                m.Unwrap();
                m.Unwrap();
                m.Unwrap();

                message = m.Unwrap().ToString();
            };

            var poller = new Poller(new List<ZmqSocket>() {Socket});

            this.Socket.SendAll(outp);

            poller.Poll(new TimeSpan(0, 0, 0, 5));

            return message;
        }
Example #21
0
        private void SendReceive()
        {
            using (var socket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.DEALER, TimeSpan.FromMilliseconds(100)))
            {
                //Connect to inbound address
                socket.Connect(this.brokerBackendAddress);

                byte[] buffer = new byte[1024];

                //these variables are a hack to ensure safe usage inside the socket events.
                var sendTimeoutIncr = 10;
                var sendTimeoutMax = 100;
                var sendTimeout = 0;

                socket.ReceiveReady += (s, e) =>
                {
                    byte[] callerId;
                    byte[] requestBytes;

                    int readBytes;
                    callerId = e.Socket.Receive(buffer, out readBytes);
                    if (readBytes > 0)
                    {
                        callerId = callerId.Slice(readBytes);
                        requestBytes = e.Socket.Receive(buffer, out readBytes);
                        this.OnRequest(callerId, requestBytes.Slice(readBytes));
                    }

                    sendTimeout = 0;
                };

                socket.SendReady += (s, e) =>
                {
                    //This delegate shouldn't need to be invoked when there are no items in the responsesQueue

                    //Tweaking the sendTimeout and blocking for longer periods on TryTake
                    //is a hack because the current clrzmq binding version doesn't support
                    //polling on the socket's output event directly. The previous version supported it.
                    Tuple<byte[], byte[]> response;
                    if (sendTimeout != 0 ?
                        this.responsesQueue.TryTake(out response, sendTimeout) :
                        this.responsesQueue.TryTake(out response))
                    {
                        e.Socket.SendMore(response.Item1); //callerId
                        e.Socket.Send(response.Item2); //response
                    }
                    else
                    {
                        if (sendTimeout < sendTimeoutMax)
                        {
                            sendTimeout += sendTimeoutIncr;
                        }
                    }
                };

                //previous clrzmq binding supported different pollitems, per socket-event type and not per socket only
                var poller = new ZeroMQ.Poller(new ZeroMQ.ZmqSocket[] { socket });
                var pollTimeout = TimeSpan.FromMilliseconds(10);

                while (Interlocked.Read(ref this.running) == 1)
                {
                    poller.Poll(pollTimeout);
                }
            }
        }
Example #22
0
        void ServerThread()
        {
            using (context ?? (context = ZmqContext.Create()))
            using (subscribeSocket = context.CreateSocket(SocketType.XSUB))
            using (publishSocket = context.CreateSocket(SocketType.XPUB))
            {
                publishSocket.Bind(PublishAddress);
                subscribeSocket.Bind(SubscribeAddress);

                publishSocket.ReceiveReady += publishSocket_ReceiveReady;
                subscribeSocket.ReceiveReady += subscribeSocket_ReceiveReady;

                var poller = new Poller(new List<ZmqSocket> { subscribeSocket, publishSocket });

                InitializationDone.Set();

                while (true)
                {
                    poller.Poll();
                }
            }
        }
Example #23
0
        //  ---------------------------------------------------------------------
        //  This is our server task
        //  It uses the multithreaded server model to deal requests out to a pool
        //  of workers and route replies back to clients. One worker can handle
        //  one request at a time but one client can talk to multiple workers at
        //  once.
        private static void ServerTask()
        {
            var workers = new List<Thread>(5);
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.DEALER))
                {
                    frontend.Bind("tcp://*:5570");
                    backend.Bind("inproc://backend");

                    for (int workerNumber = 0; workerNumber < 5; workerNumber++)
                    {
                        workers.Add(new Thread(ServerWorker));
                        workers[workerNumber].Start(context);
                    }

                    //  Switch messages between frontend and backend
                    frontend.ReceiveReady += (s, e) =>
                    {
                        var zmsg = new ZMessage(e.Socket);
                        zmsg.Send(backend);
                    };

                    backend.ReceiveReady += (s, e) =>
                    {
                        var zmsg = new ZMessage(e.Socket);
                        zmsg.Send(frontend);
                    };

                    var poller = new Poller(new List<ZmqSocket> { frontend, backend });

                    while (true)
                    {
                        poller.Poll();
                    }
                }
            }
        }
Example #24
0
        private void SendReceive()
        {
            using (var frontendSocket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.ROUTER, TimeSpan.FromMilliseconds(1)))
            {
                //Bind client outbound
                frontendSocket.Bind(this.frontendAddress);

                using (var backendSocket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.DEALER, TimeSpan.FromMilliseconds(1)))
                {
                    //Bind server inbound
                    backendSocket.Bind(this.backendAddress);

                    byte[] buffer = new byte[1024];

                    //queue messages between frontend socket and backend socket
                    frontendSocket.ReceiveReady += (s, e) =>
                    {
                        byte[] clientId;
                        byte[] frame;

                        int readBytes;

                        clientId = frontendSocket.Receive(buffer, out readBytes);
                        if (readBytes > 0)
                        {
                            backendSocket.Send(clientId, readBytes, SocketFlags.SendMore);
                            frame = frontendSocket.Receive(buffer, out readBytes);

                            while (frontendSocket.ReceiveMore)
                            {
                                backendSocket.Send(frame, readBytes, SocketFlags.SendMore);
                                frame = frontendSocket.Receive(buffer, out readBytes);
                            }

                            backendSocket.Send(frame, readBytes, SocketFlags.None);
                        }
                    };

                    //forward responses from backend socket to frontend socket
                    backendSocket.ReceiveReady += (s, e) =>
                    {
                        byte[] clientId;
                        byte[] frame;

                        int readBytes;

                        clientId = backendSocket.Receive(buffer, out readBytes);
                        if (readBytes > 0)
                        {
                            frontendSocket.Send(clientId, readBytes, SocketFlags.SendMore);
                            frame = backendSocket.Receive(buffer, out readBytes);

                            while (backendSocket.ReceiveMore)
                            {
                                frontendSocket.Send(frame, readBytes, SocketFlags.SendMore);
                                frame = backendSocket.Receive(buffer, out readBytes);
                            }

                            frontendSocket.Send(frame, readBytes, SocketFlags.None);
                        }
                    };

                    var poller      = new ZeroMQ.Poller(new ZeroMQ.ZmqSocket[] { frontendSocket, backendSocket });
                    var pollTimeout = TimeSpan.FromMilliseconds(1);

                    while (Interlocked.Read(ref this.running) == 1)
                    {
                        poller.Poll(pollTimeout);
                    }
                }
            }
        }
Example #25
0
        public static String RequestService(
            String address = "tcp://127.0.0.1:5555",
            String service = "mmi.service")
        {
            using (var context = ZmqContext.Create())
            {
                var socket = context.CreateSocket(SocketType.REQ);
                socket.Linger = new TimeSpan(500*TimeSpan.TicksPerMillisecond);
                String reply = String.Empty;
                socket.Connect(address);

                var msg = new List<String>()
                            {
                                MDP.C_CLIENT,
                                service,
                                "HERRO"
                            };

                socket.SendAll(msg);

                socket.ReceiveReady +=
                    (sender, args) => reply = args.Socket.ReceiveMessage().Select(f => (byte[]) f).ToList().ToStringBlob();

                var poller = new Poller(new [] {socket});
                poller.Poll(new TimeSpan(750*TimeSpan.TicksPerMillisecond));
                socket.Close();

                return reply;
            }
        }
Example #26
0
        private void StartRouting()
        {
            if (_routing) return;

            Info("ROUTER: Started");
            Info(String.Format("ROUTER: Frontend Port: {0} Backend Port: {1}", _frontendPort, _backendPort ));

            _routingThread = new Thread(() =>
            {
                PrepareSockets();
                //PollItem[] pollItems = new PollItem[2];
                //pollItems[0] = _frontendSocket.CreatePollItem(IOMultiPlex.POLLIN);
                //pollItems[0].PollInHandler += new PollHandler(FrontendPollInHandler);

                //pollItems[1] = _backendSocket.CreatePollItem(IOMultiPlex.POLLIN);
                //pollItems[1].PollInHandler += new PollHandler(BackendPollInHandler);
                var p = new Poller();
                p.AddSocket(_frontendSocket);
                p.AddSocket(_backendSocket);

                //p.AddSockets(new [] { _frontendSocket, _backendSocket });
                _routing = true;
                while (_routing)
                {
                    try
                    {
                        var ret = p.Poll();
                        if (ret == ZeroMQ.ErrorCode.ETERM || ret == ZeroMQ.ErrorCode.EFAULT || ret == ZeroMQ.ErrorCode.EINTR)
                        {
                            _routing = false;
                        }
                    }
                    catch (ZeroMQ.ZmqException)
                    {
                        _routing = false;
                    }
                    catch (System.Exception ex)
                    {
                        Logger.Instance.Error(ex);
                        _routing = false;
                    }
                }

                _frontendSocket.Dispose();
                _backendSocket.Dispose();

                _frontendSocket = null;
                _backendSocket = null;

                _routingThread = null;
                _routing = false;

                Logger.Instance.Info("ROUTER: Terminated gracefully");
            });

            if (_routingThread != null)
            {
                _routingThread.IsBackground = true;
                _routingThread.Start();
            }
        }
Example #27
0
        /// <summary>
        /// Creates a request using the input and MDP.Client.request (Majordomo-Protocol).
        /// Essentially: 
        /// prepends 
        ///    C_CLIENT_B,
        ///    service
        /// 
        /// To the message as input and sends it to the specified broker (at _address)
        /// </summary>
        /// <param name="sendThis"></param>
        /// <returns></returns>
        public List<byte[]> SendReceiveRaw(List<byte[]> sendThis)
        {
            var outp = MDP.Client.Request(this.Service, sendThis);
            outp.Prepend(new[] {new byte[0]});

            List<byte[]> message = new List<byte[]>();

            Socket.ReceiveReady += (sender, args) =>
                                   {
                                       message = args.Socket.ReceiveMessage().Select(frame => frame.Buffer).ToList();
                                   };

            var poller = new Poller(new List<ZmqSocket>() { Socket });

            this.Socket.SendAll(outp);

            poller.Poll(new TimeSpan(0, 0, 0, 10));

            return message;
        }
Example #28
0
        private static void Start(Object cancelationToken)
        {
            router = context.CreateSocket(SocketType.ROUTER);
            dealer = context.CreateSocket(SocketType.DEALER);
            routerEndpoint = String.Format("inproc://router");
            workersEndpoint = String.Format("inproc://workers");

            router.Bind(routerEndpoint);
            router.ReceiveReady += new EventHandler<SocketEventArgs>(router_ReceiveReady);
            dealer.Bind(workersEndpoint);
            dealer.ReceiveReady += new EventHandler<SocketEventArgs>(dealer_ReceiveReady);
             Poller poller = new Poller(new[] { router, dealer });
            var token = (CancellationToken)cancelationToken;

            workerThreads = new Thread[1];
            for (int threadId = 0; threadId < workerThreads.Length; threadId++)
            {
                workerThreads[threadId] = new Thread(WorkerRoutine);
                workerThreads[threadId].Start(context);
            }

            senderThreads = new Thread[1];
            for (int threadId = 0; threadId < senderThreads.Length; threadId++)
            {
                senderThreads[threadId] = new Thread(SenderRoutine);
                senderThreads[threadId].Start(token);
            }

            while (!token.IsCancellationRequested)
            {
                poller.Poll(TimeSpan.FromMilliseconds(100));
            }
            // to close asockets we have to wait finishing of current operation first
        }
Example #29
0
        private static void Start1(Object cancelationToken)
        {
            router = context.CreateSocket(SocketType.REQ);
            router.Connect("tcp://127.0.0.1:5000");
            router.ReceiveReady += new EventHandler<SocketEventArgs>(router_ReceiveReady1);
            router.SendReady += new EventHandler<SocketEventArgs>(router_SendReady);

            Poller poller = new Poller(new[] { router });
            var token = (CancellationToken)cancelationToken;

            while (!token.IsCancellationRequested)
            {
                poller.Poll(TimeSpan.FromMilliseconds(100));
            }
            router.Disconnect("tcp://127.0.0.1:5000");
        }
Example #30
0
        public void Work()
        {
            sock.Bind(addr);
            sock.Linger = new TimeSpan(250*TimeSpan.TicksPerMillisecond);

            sock.ReceiveReady += (sender, args) =>
                                 {
                                     var received = args.Socket.ReceiveMessage();
                                     args.Socket.SendMessage(received);
                                 };

            var poller = new Poller(new[] {sock});

            while (true)
            {
                poller.Poll();
            }
        }
Example #31
0
        private void SendReceive()
        {
            using (var frontendSocket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.ROUTER, TimeSpan.FromMilliseconds(1)))
            {
                //Bind client outbound
                frontendSocket.Bind(this.frontendAddress);

                using (var backendSocket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.DEALER, TimeSpan.FromMilliseconds(1)))
                {
                    //Bind server inbound
                    backendSocket.Bind(this.backendAddress);

                    byte[] buffer = new byte[1024];

                    //queue messages between frontend socket and backend socket
                    frontendSocket.ReceiveReady += (s, e) =>
                    {
                        byte[] clientId;
                        byte[] frame;

                        int readBytes;
                        
                        clientId = frontendSocket.Receive(buffer, out readBytes);
                        if (readBytes > 0)
                        {
                            backendSocket.Send(clientId, readBytes, SocketFlags.SendMore);
                            frame = frontendSocket.Receive(buffer, out readBytes);

                            while (frontendSocket.ReceiveMore)
                            {
                                backendSocket.Send(frame, readBytes, SocketFlags.SendMore);
                                frame = frontendSocket.Receive(buffer, out readBytes);
                            }

                            backendSocket.Send(frame, readBytes, SocketFlags.None);
                        }
                    };

                    //forward responses from backend socket to frontend socket
                    backendSocket.ReceiveReady += (s, e) =>
                    {
                        byte[] clientId;
                        byte[] frame;

                        int readBytes;
                        
                        clientId = backendSocket.Receive(buffer, out readBytes);
                        if (readBytes > 0)
                        {
                            frontendSocket.Send(clientId, readBytes, SocketFlags.SendMore);
                            frame = backendSocket.Receive(buffer, out readBytes);

                            while (backendSocket.ReceiveMore)
                            {
                                frontendSocket.Send(frame, readBytes, SocketFlags.SendMore);
                                frame = backendSocket.Receive(buffer, out readBytes);
                            }

                            frontendSocket.Send(frame, readBytes, SocketFlags.None);
                        }
                    };

                    var poller = new ZeroMQ.Poller(new ZeroMQ.ZmqSocket[] { frontendSocket, backendSocket });
                    var pollTimeout = TimeSpan.FromMilliseconds(1);

                    while (Interlocked.Read(ref this.running) == 1)
                    {
                        poller.Poll(pollTimeout);
                    }
                }
            }
        }
        private void SendReceive()
        {
            using (var socket = this.zmqContext.CreateNonBlockingSocket(ZeroMQ.SocketType.DEALER, TimeSpan.FromMilliseconds(1)))
            {
                //Connect to outbound address
                socket.Connect(this.brokerFrontendAddress);

                //these variables are a hack to ensure safe usage inside the socket events.
                var canSend        = false;
                var canReceive     = false;
                int?tryTakeTimeout = null;

                socket.SendReady += (s, e) =>
                {
                    if (canSend)
                    {
                        byte[] request;
                        if (
                            tryTakeTimeout.HasValue ?
                            this.requestsQueue.TryTake(out request, tryTakeTimeout.Value) :
                            this.requestsQueue.TryTake(out request))
                        {
                            e.Socket.Send(request);
                        }
                    }
                };

                byte[] buffer = new byte[1024];

                socket.ReceiveReady += (s, e) =>
                {
                    if (canReceive)
                    {
                        int readBytes;

                        byte[] response = e.Socket.Receive(buffer, out readBytes);

                        if (readBytes > 0)
                        {
                            this.OnResponse(response.Slice(readBytes));
                        }
                    }
                };

                var poller = new ZeroMQ.Poller(new ZeroMQ.ZmqSocket[] { socket });

                var pollTimeout = TimeSpan.FromMilliseconds(10);

                while (Interlocked.Read(ref this.running) == 1)
                {
                    tryTakeTimeout = null;

                    //idle
                    if (this.requestsQueue.Count == 0 && this.requestCallbacks.Count == 0)
                    {
                        //can't do anything except wait for a request to be sent
                        canReceive     = false;
                        canSend        = true;
                        tryTakeTimeout = 1000;
                    }
                    else if (this.requestsQueue.Count == 0 && this.requestCallbacks.Count > 0)
                    {
                        canSend    = false;
                        canReceive = true;
                    }
                    else if (this.requestsQueue.Count > 0 && this.requestCallbacks.Count == 0)
                    {
                        canSend    = true;
                        canReceive = false;
                    }
                    else
                    {
                        canSend    = true;
                        canReceive = true;
                    }

                    poller.Poll(pollTimeout);
                }
            }
        }