Пример #1
0
        public static void PSEnvPub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pubsub envelope publisher
            //
            // Author: metadings
            //

            // Prepare our context and publisher
            using (var context = ZContext.Create())
                using (var publisher = ZSocket.Create(context, ZSocketType.PUB))
                {
                    publisher.Linger = TimeSpan.Zero;
                    publisher.Bind("tcp://*:5563");

                    while (true)
                    {
                        // Write two messages, each with an envelope and content
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("A"));
                            message.Add(new ZFrame("We don't want to see this"));
                            publisher.Send(message);
                        }
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("B"));
                            message.Add(new ZFrame("We would like to see this"));
                            publisher.Send(message);
                        }
                        Thread.Sleep(1000);
                    }
                }
        }
Пример #2
0
        private void subThread_DoWork(object sender, DoWorkEventArgs e)
        {
            using (var ctx = ZContext.Create())
            {
                using (var socket = new ZSocket(ctx, ZSocketType.SUB))
                {
                    socket.Connect("tcp://127.0.0.1:5000");
                    //socket.Subscribe("Shopping");
                    socket.SubscribeAll();

                    while (true)
                    {
                        var zmqMessage = socket.ReceiveMessage();

                        var msgTitle = zmqMessage[0].ReadString(Encoding.UTF8);

                        ShoppingBasket shoppingBasket = JsonFrame.DeSerialize <ShoppingBasket>(zmqMessage[1]);

                        Console.WriteLine("SUB; Received: ");
                        Console.WriteLine("\t" + msgTitle);

                        var msg2 = JsonSerializer.SerializeToString <ShoppingBasket>(shoppingBasket);
                        Console.WriteLine("\t" + msg2);
                    }
                }
            }
        }
Пример #3
0
        public void Start()
        {
            subThread         = new BackgroundWorker();
            subThread.DoWork += new DoWorkEventHandler(subThread_DoWork);
            subThread.RunWorkerAsync();

            using (var ctx = ZContext.Create())
            {
                using (var socket = new ZSocket(ctx, ZSocketType.PUB))
                {
                    socket.Bind("tcp://127.0.0.1:5000");
                    while (true)
                    {
                        Thread.Sleep(1000);
                        // Create a ZmqMessage containing 3 frames
                        ZMessage zmqMessage = new ZMessage();
                        zmqMessage.Append(new ZFrame(Encoding.UTF8.GetBytes("My Frame 01")));
                        zmqMessage.Append(new ZFrame(Encoding.UTF8.GetBytes("My Frame 02")));
                        zmqMessage.Append(new ZFrame(Encoding.UTF8.GetBytes("My Frame 03")));

                        Console.WriteLine("PUB; publishing: ");
                        foreach (var msg in zmqMessage)
                        {
                            Console.WriteLine("\t" + msg.ReadString(Encoding.UTF8));
                        }
                        socket.SendMessage(zmqMessage);
                    }
                }
            }
        }
Пример #4
0
        public static void Espresso(IDictionary <string, string> dict, string[] args)
        {
            //
            // Espresso Pattern
            // This shows how to capture data using a pub-sub proxy
            //
            // Author: metadings
            //

            using (var context = ZContext.Create())
                using (var subscriber = ZSocket.Create(context, ZSocketType.XSUB))
                    using (var publisher = ZSocket.Create(context, ZSocketType.XPUB))
                        using (var listener = ZSocket.Create(context, ZSocketType.PAIR))
                        {
                            new Thread(() => Espresso_Publisher(context)).Start();
                            new Thread(() => Espresso_Subscriber(context)).Start();
                            new Thread(() => Espresso_Listener(context)).Start();

                            subscriber.Connect("tcp://127.0.0.1:6000");
                            publisher.Bind("tcp://*:6001");
                            listener.Bind("inproc://listener");

                            ZError error;
                            if (!ZContext.Proxy(subscriber, publisher, listener, out error))
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;             // Interrupted
                                }
                                throw new ZException(error);
                            }
                        }
        }
Пример #5
0
        public static void MTServer(IDictionary <string, string> dict, string[] args)
        {
            //
            // Multithreaded Hello World server
            //
            // Author: metadings
            //

            // Socket to talk to clients and
            // Socket to talk to workers
            using (var context = ZContext.Create())
                using (var clients = ZSocket.Create(context, ZSocketType.ROUTER))
                    using (var workers = ZSocket.Create(context, ZSocketType.DEALER))
                    {
                        clients.Bind("tcp://*:5555");
                        workers.Bind("inproc://workers");

                        // Launch pool of worker threads
                        for (int i = 0; i < 5; ++i)
                        {
                            var thread = new Thread(() => MTServer_Worker(context));
                            thread.Start();
                        }

                        // Connect work threads to client threads via a queue proxy
                        ZContext.Proxy(clients, workers);
                    }
        }
Пример #6
0
        public static void PSEnvSub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pubsub envelope subscriber
            //
            // Author: metadings
            //

            // Prepare our context and subscriber
            using (var context = ZContext.Create())
                using (var subscriber = ZSocket.Create(context, ZSocketType.SUB))
                {
                    subscriber.Connect("tcp://127.0.0.1:5563");
                    subscriber.Subscribe("B");

                    while (true)
                    {
                        using (ZMessage message = subscriber.ReceiveMessage())
                        {
                            // Read envelope with address
                            string address = message[0].ReadString();

                            // Read message contents
                            string contents = message[1].ReadString();

                            Console.WriteLine("[{0}] {1}", address, contents);
                        }
                    }
                }
        }
Пример #7
0
        public static void HWClient(IDictionary <string, string> dict, string[] args)
        {
            //
            // Hello World client
            //
            // Authors: Pieter Hintjens, Uli Riehm
            //

            // Create
            using (var context = ZContext.Create())
                using (var requester = ZSocket.Create(context, ZSocketType.REQ))
                {
                    // Connect
                    requester.Connect("tcp://127.0.0.1:5555");

                    for (int n = 0; n < 10; ++n)
                    {
                        string requestText = "Hello";
                        Console.Write("Sending {0}...", requestText);

                        // Send
                        using (var request = new ZFrame(requestText))
                        {
                            requester.Send(request);
                        }

                        // Receive
                        using (ZFrame reply = requester.ReceiveFrame())
                        {
                            Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());
                        }
                    }
                }
        }
Пример #8
0
        void subThread_DoWork(object sender, DoWorkEventArgs e)
        {
            using (var ctx = ZContext.Create())
            {
                using (var socket = new ZSocket(ctx, ZSocketType.SUB))
                {
                    socket.Connect("tcp://127.0.0.1:5000");

                    //can set filter
                    //socket.Subscribe("prefixdemo");
                    socket.SubscribeAll();


                    while (true)
                    {
                        var zmqMessage    = socket.ReceiveMessage();
                        var frameContents = zmqMessage
                                            .Select(f => f.ReadString(Encoding.UTF8)).ToList();
                        Console.WriteLine("SUB; Received: ");
                        foreach (var frameContent in frameContents)
                        {
                            Console.WriteLine("\t" + frameContent);
                        }
                    }
                }
            }
        }
Пример #9
0
        static int FLClient1_MAX_RETRIES = 3;           // Before we abandon

        public static void FLClient1(IDictionary <string, string> dict, string[] args)
        {
            //
            // Freelance client - Model 1
            // Uses REQ socket to query one or more services
            //
            // Authors: Pieter Hintjens, Uli Riehm
            //

            if (args == null || args.Length < 1)
            {
                Console.WriteLine("I: syntax: {0} FLClient1 [endpoint]", AppDomain.CurrentDomain.FriendlyName);
                return;
            }

            // The client uses a Lazy Pirate strategy if it only has one server to talk
            // to. If it has two or more servers to talk to, it will try each server just
            // once:

            using (var context = ZContext.Create())
                using (var request = new ZFrame("Hello World"))
                {
                    ZFrame reply = null;

                    if (args.Length == 1)
                    {
                        // For one endpoint, we retry N times
                        string endpoint = args[0];

                        for (int retries = 0; retries < FLClient1_MAX_RETRIES; ++retries)
                        {
                            if (null != (reply = FLClient1_TryRequest(context, endpoint, request)))
                            {
                                break;                          // Successful
                            }
                            Console.WriteLine("W: no response from {0}, retrying...", endpoint);
                        }
                    }
                    else
                    {
                        // For multiple endpoints, try each at most once

                        for (int endpoint_nbr = 0; endpoint_nbr < args.Length; ++endpoint_nbr)
                        {
                            string endpoint = args[endpoint_nbr];

                            if (null != (reply = FLClient1_TryRequest(context, endpoint, request)))
                            {
                                break;                          // Successful
                            }
                            Console.WriteLine("W: no response from {0}, retrying...", endpoint);
                        }
                    }

                    if (reply != null)
                    {
                        Console.WriteLine("Service is running OK");
                    }
                }
        }
Пример #10
0
        private static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            using (var context = ZContext.Create())
            {
                using (var socket = new ZSocket(context, ZSocketType.REP))
                {
                    foreach (var bindEndPoint in options.BindEndPoints)
                    {
                        socket.Bind(bindEndPoint);
                    }

                    while (true)
                    {
                        Thread.Sleep(options.Delay);

                        var rcvdFrame = socket.ReceiveFrame();
                        var rcvdMsg   = rcvdFrame.ReadString(Encoding.UTF8);
                        Console.WriteLine("Received: " + rcvdMsg);

                        var replyMsg   = options.ReplyMessage.Replace("#msg#", rcvdMsg);
                        var replyFrame = new ZFrame(replyMsg);
                        Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);
                        socket.Send(replyFrame);
                    }
                }
            }
        }
Пример #11
0
        private static void ServerThread()
        {
            using (var context = ZContext.Create())
                using (var socket = ZSocket.Create(context, ZSocketType.REP))
                {
                    socket.Bind("tcp://*:9000");

                    foreach (int messageSize in MessageSizes)
                    {
                        var message = new byte[messageSize];

                        for (int i = 0; i < RoundtripCount; i++)
                        {
                            ZError error;
                            var    receivedBytes = socket.ReceiveBytes(message, 0, message.Length, ZSocketFlags.None, out error);

                            Debug.Assert(receivedBytes, "Ping message length did not match expected value.");

                            var sendStatus = socket.Send(message, 0, message.Length, ZSocketFlags.None, out error);

                            Debug.Assert(sendStatus, "Message was not indicated as sent.");
                        }
                    }
                }
        }
Пример #12
0
 public void Create_ViaFactoryMethod()
 {
     using (var context = ZContext.Create())
     {
         Assert.IsNotNull(context);
     }
 }
Пример #13
0
        public static void RRClient(IDictionary <string, string> dict, string[] args)
        {
            //
            // Hello World client
            // Connects REQ socket to tcp://localhost:5559
            // Sends "Hello" to server, expects "World" back
            //
            // Authors: Pieter Hintjens, Uli Riehm
            //

            // Socket to talk to server
            using (var context = ZContext.Create())
                using (var requester = ZSocket.Create(context, ZSocketType.REQ))
                {
                    requester.Connect("tcp://127.0.0.1:5559");

                    for (int n = 0; n < 10; ++n)
                    {
                        using (var request = new ZFrame("Hello"))
                        {
                            requester.Send(request);
                        }

                        using (ZFrame reply = requester.ReceiveFrame())
                        {
                            Console.WriteLine("Hello {0}!", reply.ReadString());
                        }
                    }
                }
        }
Пример #14
0
        private static void Main(string[] args)
        {
            try
            {
                var options = new Options();
                var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));
                if (!parser.ParseArguments(args, options))
                {
                    Environment.Exit(1);
                }

                using (var context = ZContext.Create())
                {
                    using (var socket = new ZSocket(context, ZSocketType.PUSH))
                    {
                        foreach (var endPoint in options.BindEndPoints)
                        {
                            socket.Bind(endPoint);
                        }

                        long msgCptr  = 0;
                        var  msgIndex = 0;

                        while (true)
                        {
                            if (msgCptr == long.MaxValue)
                            {
                                msgCptr = 0;
                            }

                            msgCptr++;
                            if (options.MaxMessage >= 0)
                            {
                                if (msgCptr > options.MaxMessage)
                                {
                                    break;
                                }
                            }

                            if (msgIndex == options.AltMessages.Count())
                            {
                                msgIndex = 0;
                            }

                            var msg = options.AltMessages[msgIndex++].Replace("#nb#", msgCptr.ToString("d2"));
                            Thread.Sleep(options.Delay);

                            Console.WriteLine("Pushing: " + msg);

                            var msgFrame = new ZFrame(msg, Encoding.UTF8);
                            socket.Send(msgFrame);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
Пример #15
0
        public static void TaskWork(IDictionary <string, string> dict, string[] args)
        {
            //
            // Task worker
            // Connects PULL socket to tcp://localhost:5557
            // Collects workloads from ventilator via that socket
            // Connects PUSH socket to tcp://localhost:5558
            // Sends results to sink via that socket
            //
            // Author: metadings
            //

            // Socket to receive messages on and
            // Socket to send messages to
            using (var context = ZContext.Create())
                using (var receiver = ZSocket.Create(context, ZSocketType.PULL))
                    using (var sink = ZSocket.Create(context, ZSocketType.PUSH))
                    {
                        receiver.Connect("tcp://127.0.0.1:5557");
                        sink.Connect("tcp://127.0.0.1:5558");

                        // Process tasks forever
                        while (true)
                        {
                            var replyBytes = new byte[4];
                            receiver.ReceiveBytes(replyBytes, 0, replyBytes.Length);
                            int workload = BitConverter.ToInt32(replyBytes, 0);
                            Console.WriteLine("{0}.", workload); // Show progress

                            Thread.Sleep(workload);              // Do the work

                            sink.Send(new byte[0], 0, 0);        // Send results to sink
                        }
                    }
        }
Пример #16
0
        static void RTReq_Worker(int i)
        {
            using (var context = ZContext.Create())
                using (var worker = ZSocket.Create(context, ZSocketType.REQ))
                {
                    worker.IdentityString = "PEER" + i;                 // Set a printable identity
                    worker.Connect("tcp://127.0.0.1:5671");

                    int total = 0;
                    while (true)
                    {
                        // Tell the broker we're ready for work
                        worker.Send(new ZFrame("Hi Boss"));

                        // Get workload from broker, until finished
                        bool finished;
                        using (ZFrame frame = worker.ReceiveFrame())
                        {
                            finished = (frame.ReadString() == "Fired!");
                        }
                        if (finished)
                        {
                            break;
                        }
                        total++;

                        // Do some random work
                        Thread.Sleep(1);
                    }

                    Console.WriteLine("Completed: PEER{0}, {1} tasks", i, total);
                }
        }
Пример #17
0
            public FreelanceClient()
            {
                // Constructor
                this.context = ZContext.Create();

                this.Actor = new ZActor(this.context, FreelanceClient.Agent);
                this.Actor.Start();
            }
Пример #18
0
            public FLClient()
            {
                // Constructor

                context       = ZContext.Create();
                socket        = ZSocket.Create(context, ZSocketType.DEALER);
                socket.Linger = GLOBAL_TIMEOUT;
            }
Пример #19
0
        // ZeroMQ rcon stuff
#if ZMQ
        #region Rcon()

        public override void Rcon(ServerRow row, int port, string password, string command)
        {
            using (var ctx = ZContext.Create())
            {
                ZSocket client, monitor;
                var     endpoint = new IPEndPoint(row.EndPoint.Address, port);
                this.CreateClientAndMonitorSockets(ctx, endpoint, password, out client, out monitor);
                using (client)
                    using (monitor)
                    {
                        while (true)
                        {
                            ZMessage msg = new ZMessage();
                            ZError   err;
                            var      poll = ZPollItem.CreateReceiver();
                            var      ev   = client.Poll(poll, ZPoll.In | ZPoll.Out | ZPoll.Err, ref msg, out err, TimeSpan.FromMilliseconds(500));
                            if (err == ZError.ETERM)
                            {
                                break;
                            }

                            var evMonitor = CheckMonitor(monitor);
                            if (evMonitor != null)
                            {
                                if (evMonitor.Item1 == ZMonitorEvents.Connected)
                                {
                                    client.Send(new ZFrame("register"));
                                    client.Send(new ZFrame(command));
                                    return;
                                }
                                if (evMonitor.Item1 == ZMonitorEvents.Closed || evMonitor.Item1 == ZMonitorEvents.Disconnected)
                                {
                                    return;
                                }
                            }

                            if (!ev)
                            {
                                continue;
                            }

                            while (true)
                            {
                                client.ReceiveMessage(ref msg, ZSocketFlags.DontWait, out err);
                                if (err != ZError.None)
                                {
                                    if (err != ZError.EAGAIN)
                                    {
                                        Console.WriteLine(err);
                                    }
                                    break;
                                }
                                Console.WriteLine(msg);
                            }
                        }
                    }
            }
        }
Пример #20
0
        public static void PushPull(IDictionary <string, string> dict, string[] args)
        {
            int who = dict.ContainsKey("--server") ? 1 : (dict.ContainsKey("--client") ? 2 : 0);

            if (args == null || args.Length < 1)
            {
                // say here were some arguments...
                args = new string[] { "World" };
            }

            // Setup the ZContext
            context = ZContext.Create();

            CancellationTokenSource cancellor0 = null;

            if (who == 0 || who == 1)
            {
                // Create the "Server" cancellor and thread
                cancellor0 = new CancellationTokenSource();
                var serverThread = new Thread(PushPull_Server);
                serverThread.Start(cancellor0.Token);
                serverThread.Join(64);
            }


            if (who == 1)
            {
                Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
                {
                    Console.WriteLine("Cancelled...");
                };

                Console.WriteLine("Running...");

                while (true)
                {
                    Thread.Sleep(64);
                }
            }
            else if (who == 0 || who == 2)
            {
                // foreach arg we are the Client, asking the Server
                foreach (string arg in args)
                {
                    PushPull_Client(arg);
                }

                Thread.Sleep(1000);
            }

            if (cancellor0 != null)
            {
                // Cancel the Server
                cancellor0.Cancel();
            }

            // we could have done here context.Terminate()
        }
Пример #21
0
 public void Start()
 {
     if (IsOpenZmqInterface)
     {
         this.context = ZContext.Create();
         ReplyThreadStart();
         PubThreadStart();
     }
 }
Пример #22
0
        private static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            using (var context = ZContext.Create())
            {
                using (var socket = new ZSocket(context, ZSocketType.REQ))
                {
                    foreach (var connectEndpoint in options.ConnectEndPoints)
                    {
                        socket.Connect(connectEndpoint);
                    }

                    long msgCptr  = 0;
                    var  msgIndex = 0;

                    while (true)
                    {
                        if (msgCptr == long.MaxValue)
                        {
                            msgCptr = 0;
                        }

                        msgCptr++;
                        if (options.MaxMessage >= 0)
                        {
                            if (msgCptr > options.MaxMessage)
                            {
                                break;
                            }
                        }

                        if (msgIndex == options.AlterMessages.Count())
                        {
                            msgIndex = 0;
                        }

                        var reqMsg = options.AlterMessages[msgIndex++].Replace("#nb#", msgCptr.ToString("d2"));
                        Thread.Sleep(options.Delay);

                        Console.WriteLine("Sending : " + reqMsg);

                        socket.Send(new ZFrame(reqMsg, Encoding.UTF8));

                        var replyFrame = socket.ReceiveFrame();

                        Console.WriteLine("Received: " + replyFrame.ReadString() + Environment.NewLine);
                    }
                }
            }
        }
Пример #23
0
        public static void RTReq(IDictionary <string, string> dict, string[] args)
        {
            //
            // ROUTER-to-REQ example
            //
            // While this example runs in a single process, that is only to make
            // it easier to start and stop the example. Each thread has its own
            // context and conceptually acts as a separate process.
            //
            // Author: metadings
            //

            using (var context = ZContext.Create())
                using (var broker = ZSocket.Create(context, ZSocketType.ROUTER))
                {
                    broker.Bind("tcp://*:5671");

                    for (int i = 0; i < RTReq_Workers; ++i)
                    {
                        int j = i;
                        new Thread(() => RTReq_Worker(j)).Start();
                    }

                    var stopwatch = new Stopwatch();
                    stopwatch.Start();

                    // Run for five seconds and then tell workers to end
                    int workers_fired = 0;
                    while (true)
                    {
                        // Next message gives us least recently used worker
                        using (ZMessage identity = broker.ReceiveMessage())
                        {
                            broker.SendMore(identity[0]);
                            broker.SendMore(new ZFrame());

                            // Encourage workers until it's time to fire them
                            if (stopwatch.Elapsed < TimeSpan.FromSeconds(5))
                            {
                                broker.Send(new ZFrame("Work harder!"));
                            }
                            else
                            {
                                broker.Send(new ZFrame("Fired!"));
                                if (++workers_fired == RTReq_Workers)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
        }
Пример #24
0
        private static void Main(string[] args)
        {
            try
            {
                var options = new Options();
                var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));
                if (!parser.ParseArguments(args, options))
                {
                    Environment.Exit(1);
                }

                using (var context = ZContext.Create())
                {
                    using (var socket = new ZSocket(context, ZSocketType.SUB))
                    {
                        if (options.SubscriptionPrefixes.Count() == 0)
                        {
                            Console.WriteLine("socket.SubscribeAll()");
                            socket.SubscribeAll();
                        }
                        else
                        {
                            foreach (var subscriptionPrefix in options.SubscriptionPrefixes)
                            {
                                socket.Subscribe(Encoding.UTF8.GetBytes(subscriptionPrefix));
                            }
                        }
                        //match the message if it beginwith the prifex.

                        foreach (var endPoint in options.ConnectEndPoints)
                        {
                            Console.WriteLine("connect to {0}", endPoint);
                            socket.Connect(endPoint);
                        }

                        while (true)
                        {
                            Thread.Sleep(options.Delay);

                            Console.WriteLine("ReceiveFrame");
                            var msgFrame = socket.ReceiveFrame();
                            var msg      = msgFrame.ReadString(Encoding.UTF8);
                            Console.WriteLine("Received: " + msg);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
Пример #25
0
        public static void PathoSub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pathological subscriber
            // Subscribes to one random topic and prints received messages
            //
            // Author: metadings
            //

            if (args == null || args.Length < 1)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ./{0} PathoSub [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                Console.WriteLine("    Endpoint  Where PathoSub should connect to.");
                Console.WriteLine("              Default is tcp://127.0.0.1:5556");
                Console.WriteLine();
                args = new string[] { "tcp://127.0.0.1:5556" };
            }

            using (var context = ZContext.Create())
                using (var subscriber = ZSocket.Create(context, ZSocketType.SUB))
                {
                    subscriber.Connect(args[0]);

                    var rnd          = new Random();
                    var subscription = string.Format("{0:D3}", rnd.Next(1000));
                    subscriber.Subscribe(subscription);

                    ZMessage msg;
                    ZError   error;
                    while (true)
                    {
                        if (null == (msg = subscriber.ReceiveMessage(out error)))
                        {
                            if (error == ZError.ETERM)
                            {
                                break;                          // Interrupted
                            }
                            throw new ZException(error);
                        }
                        using (msg)
                        {
                            if (msg[0].ReadString() != subscription)
                            {
                                throw new InvalidOperationException();
                            }
                            Console.WriteLine(msg[1].ReadString());
                        }
                    }
                }
        }
Пример #26
0
        public static void PathoPub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pathological publisher
            // Sends out 1,000 topics and then one random update per second
            //
            // Author: metadings
            //

            if (args == null || args.Length < 1)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ./{0} PathoPub [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                Console.WriteLine("    Endpoint  Where PathoPub should connect to.");
                Console.WriteLine("              Default is null, Binding on tcp://*:5556");
                Console.WriteLine();
                args = new string[] { null };
            }

            using (var context = ZContext.Create())
                using (var publisher = ZSocket.Create(context, ZSocketType.PUB))
                {
                    if (args[0] != null)
                    {
                        publisher.Connect(args[0]);
                    }
                    else
                    {
                        publisher.Bind("tcp://*:5556");
                    }

                    // Ensure subscriber connection has time to complete
                    Thread.Sleep(100);

                    // Send out all 1,000 topic messages
                    for (int topic = 0; topic < 1000; ++topic)
                    {
                        publisher.SendMore(new ZFrame(string.Format("{0:D3}", topic)));
                        publisher.Send(new ZFrame("Save Roger"));
                    }

                    // Send one random update per second
                    var rnd = new Random();
                    while (true)
                    {
                        Thread.Sleep(10);
                        publisher.SendMore(new ZFrame(string.Format("{0:D3}", rnd.Next(1000))));
                        publisher.Send(new ZFrame("Off with his head!"));
                    }
                }
        }
Пример #27
0
        public static void PubSub(IDictionary <string, string> dict, string[] args)
        {
            int who = dict.ContainsKey("--server") ? 1 : (dict.ContainsKey("--client") ? 2 : 0);

            if (args == null || args.Length < 1)
            {
                // say here were some arguments...
                args = new string[] { "World" };
            }

            // Setup the ZContext
            context = ZContext.Create();

            var cancellor0 = new CancellationTokenSource();

            if (who == 0 || who == 1)
            {
                var serverThread = new Thread(() => PubSub_Server(cancellor0.Token, args));
                serverThread.Start();
                serverThread.Join(64);
            }

            if (who == 0 || who == 2)
            {
                foreach (string arg in args)
                {
                    var clientThread = new Thread(() => PubSub_Client(cancellor0.Token, arg));
                    clientThread.Start();
                    clientThread.Join(64);
                }
            }

            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
            {
                Console.WriteLine("Cancelled...");

                if (cancellor0 != null)
                {
                    // Cancel the Server
                    cancellor0.Cancel();
                }

                // we could have done here context.Terminate()
            };

            Console.WriteLine("Running...");

            while (true)
            {
                Thread.Sleep(64);
            }
        }
Пример #28
0
        private static void ServerThread()
        {
            using (var context = ZContext.Create())
                using (var socket = ZSocket.Create(context, ZSocketType.REP))
                {
                    socket.Bind("tcp://*:8989");

                    ZFrame request = socket.ReceiveFrame();
                    Console.WriteLine(request.ReadString(Encoding.UTF8));

                    socket.SendFrame(new ZFrame(Encoding.UTF8.GetBytes("World")));
                }
        }
Пример #29
0
 public void Start()
 {
     if (IsOpenZmqInterface)
     {
         if (!IsStarted)
         {
             IsStarted = true;
         }
         this.context = ZContext.Create();
         ReplyThreadStart();
         PubThreadStart();
     }
 }
Пример #30
0
        /// <summary>
        /// Starts the <see cref="ZeroMQServer"/> synchronously and begins accepting client connections asynchronously.
        /// </summary>
        /// <exception cref="InvalidOperationException">Attempt is made to <see cref="Start()"/> the <see cref="ZeroMQServer"/> when it is running.</exception>
        public override void Start()
        {
            if (CurrentState == ServerState.NotRunning)
            {
                int maxClientConnections, maxQueueSize;

                // Initialize if needed
                if (!Initialized)
                {
                    Initialize();
                }

                // Overwrite config file if max client connections exists in connection string.
                if (m_configData.ContainsKey("maxClientConnections") && int.TryParse(m_configData["maxClientConnections"], out maxClientConnections))
                {
                    MaxClientConnections = maxClientConnections;
                }

                // Overwrite config file if max send queue size exists in connection string.
                if (m_configData.ContainsKey("maxSendQueueSize") && int.TryParse(m_configData["maxSendQueueSize"], out maxQueueSize))
                {
                    m_maxSendQueueSize = maxQueueSize;
                }

                // Overwrite config file if max receive queue size exists in connection string.
                if (m_configData.ContainsKey("maxReceiveQueueSize") && int.TryParse(m_configData["maxReceiveQueueSize"], out maxQueueSize))
                {
                    m_maxReceiveQueueSize = maxQueueSize;
                }

                // Create ZeroMQ Router socket - closest match to IServer implementation
                m_zeroMQServer                      = new ZSocket(ZContext.Create(), ZSocketType.ROUTER);
                m_zeroMQServer.Identity             = ServerID.ToByteArray();
                m_zeroMQServer.SendHighWatermark    = m_maxSendQueueSize;
                m_zeroMQServer.ReceiveHighWatermark = m_maxReceiveQueueSize;
                m_zeroMQServer.Immediate            = true;
                m_zeroMQServer.SetOption(ZSocketOption.LINGER, 0);
                m_zeroMQServer.SetOption(ZSocketOption.SNDTIMEO, 1000);
                m_zeroMQServer.SetOption(ZSocketOption.RCVTIMEO, -1);
                m_zeroMQServer.SetOption(ZSocketOption.RECONNECT_IVL, -1);
                m_zeroMQServer.IPv6 = (Transport.GetDefaultIPStack() == IPStack.IPv6);
                m_zeroMQServer.Bind(m_configData["server"]);

                // Notify that the server has been started successfully.
                OnServerStarted();

                m_receiveDataThread = new Thread(ReceiveDataHandler);
                m_receiveDataThread.IsBackground = true;
                m_receiveDataThread.Start();
            }
        }