Esempio n. 1
0
        private static void ClientThread(object UseInproc)
        {
            using (var context = ZmqContext.Create())
                using (var socket = context.CreateSocket(SocketType.REQ))
                {
                    socket.Connect((bool)UseInproc ? "inproc://abc" : "tcp://localhost:9000");

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

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

                        for (int i = 0; i < RoundtripCount; i++)
                        {
                            SendStatus sendStatus = socket.Send(msg);

                            Debug.Assert(sendStatus == SendStatus.Sent, "Message was not indicated as sent.");

                            int bytesReceived = socket.Receive(reply);

                            Debug.Assert(bytesReceived == messageSize, "Pong message did not have the expected size.");
                        }

                        watch.Stop();
                        long elapsedTime = watch.ElapsedTicks;

                        double latency = (double)elapsedTime / RoundtripCount / 2 * 1000000 / Stopwatch.Frequency;
                        Console.WriteLine("Roundtrips: {0}, MsgSz: {1,5}, Latency: {2,6} us",
                                          RoundtripCount, messageSize, latency.ToString("f2"));
                    }
                }
        }
Esempio n. 2
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket replyer = context.CreateSocket(SocketType.REP))
                {
                    replyer.Bind("tcp://*:5555");

                    bool interrupted = false;

                    Console.CancelKeyPress += delegate { interrupted = true; };

                    const string replyMessage = "World";

                    while (!interrupted)
                    {
                        string message = replyer.Receive(Encoding.Unicode);
                        Console.WriteLine("Received request: {0}", message);

                        // Simulate work, by sleeping
                        Thread.Sleep(1000);

                        // Send reply back to client
                        replyer.Send(replyMessage, Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 3
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket subscriber = context.CreateSocket(SocketType.SUB), syncClient = context.CreateSocket(SocketType.REQ))
                {
                    subscriber.Connect("tcp://localhost:5561");
                    subscriber.Subscribe(Encoding.Unicode.GetBytes(string.Empty));

                    syncClient.Connect("tcp://localhost:5562");

                    //  - send a synchronization request
                    syncClient.Send("", Encoding.Unicode);
                    //  - wait for synchronization reply
                    syncClient.Receive(Encoding.Unicode);

                    int receivedUpdates = 0;
                    while (!subscriber.Receive(Encoding.Unicode).Equals("END"))
                    {
                        receivedUpdates++;
                    }

                    Console.WriteLine("Received {0} updates.", receivedUpdates);
                }
            }

            Console.ReadKey();
        }
Esempio n. 4
0
        public Publisher(string _guid, string _host, int _port, ZmqContext _ctx)
        {
            guid = _guid;
            host = _host;
            port = _port;

            if (_ctx == null)
            {
                ctx = ZmqContext.Create();
            }
            else
            {
                ctx = _ctx;
            }
            socket = ctx.CreateSocket(SocketType.PUB);
            var bindString = String.Empty;

            if (port > 0)
            {
                bindString = String.Format("tcp://*:{0}", port);
            }
            else
            {
                bindString = String.Format("inproc://{0}", guid.ToLower());
            }
            socket.Bind(bindString);
            log.InfoFormat("Publisher successfuly binded on {0}", bindString);
            socket.SendHighWatermark = 1000000;
            socket.SendBufferSize    = 128 * 1024;
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (var subscriber = context.CreateSocket(ZeroMQ.SocketType.SUB))
                    using (var syncclient = context.CreateSocket(ZeroMQ.SocketType.REQ))
                    {
                        //subscriber.Connect("tcp://172.16.73.88:3385");
                        subscriber.Connect("tcp://192.168.179.128:3385");

                        subscriber.SubscribeAll();
                        Thread.Sleep(1);

                        //syncclient.Connect("tcp://172.16.73.88:4950");
                        syncclient.Connect("tcp://192.168.179.128:4950");


                        syncclient.SendFrame(new Frame(Encoding.UTF8.GetBytes("Sync me")));
                        var repMsg = Encoding.UTF8.GetString(syncclient.ReceiveFrame().Buffer);

                        while (true)
                        {
                            var pubMsg = subscriber.ReceiveMessage();

                            Console.WriteLine(Encoding.UTF8.GetString(pubMsg[0].Buffer));
                        }
                    }
            }
        }
Esempio n. 6
0
        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 ctx = ZmqContext.Create())
                {
                    using (var socket = ctx.CreateSocket(SocketType.PULL))
                    {
                        foreach (var endPoint in options.bindEndPoints)
                        {
                            socket.Bind(endPoint);
                        }

                        while (true)
                        {
                            Thread.Sleep(options.delay);
                            var msg = socket.Receive(Encoding.UTF8);
                            Console.WriteLine("Received: " + msg);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
Esempio n. 7
0
 public ZmqPublisher(string endpoint)
 {
     _endpoint = endpoint;
     _context = ZmqContext.Create();
     _socket = _context.CreateSocket(SocketType.PUB);
     _socket.Bind(_endpoint);
 }
Esempio n. 8
0
        public void Start(U startResponse)
        {
            try
            {
                using (var context = ZmqContext.Create())
                {
                    using (var socket = context.CreateSocket(SocketType.REQ))
                    {
                        foreach (var connectEndpoint in _bindEndPoints)
                        {
                            socket.Connect(connectEndpoint);
                        }

                        var nextResponse = startResponse;

                        while (true)
                        {
                            var responseFrame = new Frame(nextResponse.ToByteArray());
                            socket.SendFrame(responseFrame);

                            var messageFrame = socket.ReceiveFrame();
                            var request      = SerializationMethods.FromByteArray <T>(messageFrame.Buffer);

                            var reply = _process(request);

                            nextResponse = reply;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 9
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), sender = context.CreateSocket(SocketType.PUSH))
                {
                    receiver.Connect("tcp://localhost:5557");
                    sender.Connect("tcp://localhost:5558");

                    while (true)
                    {
                        string task = receiver.Receive(Encoding.Unicode);

                        //  Simple progress indicator for the viewer;
                        Console.WriteLine("{0}.", task);

                        int sleepTime = Convert.ToInt32(task);
                        Thread.Sleep(sleepTime);

                        // Send 'result' to the sink
                        sender.Send("", Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 10
0
        private static void ClientTask()
        {
            using (var ctx = ZmqContext.Create())
            {
                using (var client = ctx.CreateSocket(SocketType.REQ))
                {
                    ZHelpers.SetID(client, Encoding.Unicode);
                    client.Connect("tcp://localhost:5555");

                    while (true)
                    {
                        //  Send request, get repl
                        client.Send("HELLO", Encoding.Unicode);
                        string reply = client.Receive(Encoding.Unicode);

                        if (string.IsNullOrEmpty(reply))
                        {
                            break;
                        }

                        Console.WriteLine("Client: {0}", reply);
                    }
                }
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            using (ZmqContext context = ZmqContext.Create())
                using (ZmqSocket server = context.CreateSocket(SocketType.SUB))
                {
                    server.SubscribeAll();
                    for (int i = 1; i < 255; i++)
                    {
                        string address = string.Format("tcp://192.168.11.{0}:9000", i);
                        try
                        {
                            server.Connect(address);
                        }
                        catch
                        {
                        }
                    }

                    while (true)
                    {
                        // Wait for next request from client
                        string message = server.Receive(Encoding.ASCII);
                        Console.WriteLine("{0}: {1}", DateTime.Now.ToShortTimeString(), message);
                    }
                }
        }
Esempio n. 12
0
        public void IsAConnection()
        {
            ZmqContext zmqContext = ZmqContext.Create();

            Daytona.Store.Connection connection = new Daytona.Store.Connection(zmqContext);
            Assert.IsInstanceOfType(connection, typeof(Daytona.Store.Connection));
        }
Esempio n. 13
0
 public ZmqOutboundSocket(ZmqContext context, PeerId peerId, string endPoint, IZmqSocketOptions options)
 {
     _context = context;
     _peerId  = peerId;
     _options = options;
     EndPoint = endPoint;
 }
Esempio n. 14
0
        public void Start()
        {
            try
            {
                using (var context = ZmqContext.Create())
                {
                    using (var socket = context.CreateSocket(SocketType.PUSH))
                    {
                        foreach (var bindEndPoint in _bindEndPoints)
                        {
                            socket.Connect(bindEndPoint);
                        }

                        while (true)
                        {
                            var message = _requests.Take();
                            var frame   = new Frame(message.ToByteArray());
                            socket.SendFrame(frame);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 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();
                    }
                }
            }
        }
Esempio n. 16
0
        private static void ClientTask()
        {
            using (var ctx = ZmqContext.Create())
            {
                using (var client = ctx.CreateSocket(SocketType.REQ))
                {
                    ZHelpers.SetID(client, Encoding.Unicode);
                    client.Connect(localFeAddress);

                    while (true)
                    {
                        client.Send("HELLO", Encoding.Unicode);
                        string reply = client.Receive(Encoding.Unicode);

                        if (string.IsNullOrEmpty(reply))
                        {
                            break;
                        }

                        Console.WriteLine("Client: {0}", reply);

                        Thread.Sleep(1000);
                    }
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Starts the nodelet.
        /// </summary>
        /// <param name="options">The nodelet command options.</param>
        public void Start(Options options)
        {
            using (var context = ZmqContext.Create())
                using (var subscriber = context.CreateSocket(SocketType.SUB))
                {
                    if (string.IsNullOrEmpty(options.SubscriptionChannel))
                    {
                        Console.WriteLine("Subscribing to all channels.");
                        subscriber.SubscribeAll();
                    }
                    else
                    {
                        Console.WriteLine("Subscribing to: {0}", options.SubscriptionChannel);
                        subscriber.Subscribe(Encoding.Unicode.GetBytes(options.SubscriptionChannel));
                    }

                    var endpoint = string.Format("tcp://{0}", options.SocketConnect);
                    Console.WriteLine("Connecting to: {0}", endpoint);
                    subscriber.Connect(endpoint);

                    while (true)
                    {
                        var message = subscriber.Receive(Encoding.Unicode);
                        Console.WriteLine("Recieved message: {0}", message);
                    }
                }
        }
 internal ZmqMessageSender(Uri serviceUri)
 {
     context = ZmqContext.Create();
     socket = context.CreateSocket(SocketType.REQ);
     var address = string.Format("tcp://{0}:{1}", serviceUri.Host, serviceUri.Port);
     socket.Connect(address);
 }
Esempio n. 19
0
        private static void WorkerTask()
        {
            using (var ctx = ZmqContext.Create())
            {
                using (var worker = ctx.CreateSocket(SocketType.REQ))
                {
                    ZHelpers.SetID(worker, Encoding.Unicode);
                    worker.Connect(localBeAddress);

                    var msg = new ZMessage("READY");
                    msg.Send(worker);

                    while (true)
                    {
                        var recvMsg = new ZMessage(worker);
                        Console.WriteLine("Worker: {0}", recvMsg.BodyToString());

                        Thread.Sleep(1000);

                        recvMsg.StringToBody("OK");
                        recvMsg.Send(worker);
                        //var okmsg = new ZMessage("OK");
                        //okmsg.Send(worker);
                    }
                }
            }
        }
Esempio n. 20
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                var randomizer = new Random(DateTime.Now.Millisecond);

                using (var server = context.CreateSocket(SocketType.REP))
                {
                    server.Bind("tcp://*:5555");

                    var cycles = 0;

                    while (true)
                    {
                        var request = server.Receive(Encoding.Unicode);
                        cycles++;

                        if (cycles > 3 && randomizer.Next(2) == 0)
                        {
                            Console.WriteLine("Simulating a crash");
                            break;
                        }
                        else if (cycles < 3 && randomizer.Next(2) == 0)
                        {
                            Console.WriteLine("Simulating CPU overload");
                            Thread.Sleep(2000);
                        }

                        Console.WriteLine("Normal request ({0})", request);
                        Thread.Sleep(1000);
                        server.Send(request, Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 21
0
        private static void WorkerTask()
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket worker = context.CreateSocket(SocketType.REQ))
                {
                    ZHelpers.SetID(worker, Encoding.Unicode);
                    worker.Connect("tcp://localhost:5556");

                    //  Tell broker we're ready for work
                    worker.Send("READY", Encoding.Unicode);

                    while (true)
                    {
                        //  Read and save all frames until we get an empty frame
                        //  In this example there is only 1 but it could be more
                        string address = worker.Receive(Encoding.Unicode);
                        string empty   = worker.Receive(Encoding.Unicode);

                        //  Get request, send reply
                        string request = worker.Receive(Encoding.Unicode);
                        Console.WriteLine("Worker: {0}", request);

                        worker.SendMore(address, Encoding.Unicode);
                        //worker.SendMore();
                        worker.Send("OK", Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 22
0
 public ZmqOutboundSocket(ZmqContext context, PeerId peerId, string endPoint, IZmqSocketOptions options)
 {
     _context = context;
     _peerId = peerId;
     _options = options;
     EndPoint = endPoint;
 }
Esempio n. 23
0
        private static ZmqSocket GetConnectedPublishSocket(ZmqContext context)
        {
            ZmqSocket publisher = context.CreateSocket(SocketType.PUB);

            publisher.Connect("tcp://localhost:5556");
            return(publisher);
        }
Esempio n. 24
0
 public static void Main(string[] args)
 {
     using (var context = ZmqContext.Create())
     {
         using (ZmqSocket publisher = context.CreateSocket(SocketType.PUB))
         {
             // your first potential issue lies here, if you're not
             // populating your addresses properly then you're not going to
             // bind appropriately
             // Test by hard coding the address
             publisher.Bind("tcp://127.0.0.1:5000");
             int msgIndex = 0;
             while (true)
             {
                 // your second potential issue lies here, if your logic
                 // short circuits your send, that'll throw a wrench in the
                 // works
                 // Test by removing the logic and just sending a bunch of
                 // messages
                 var msg = "Message: " + msgIndex;     // simplify
                 Console.WriteLine("Publishing: " + msg);
                 socket.Send(msg, Encoding.UTF8);
                 Thread.Sleep(500);     // hard code
                 msgIndex++;
                 if (msgIndex > 1500)
                 {
                     break;                      // hard code the break
                 }
             }
         }
     }
 }
Esempio n. 25
0
        private static string Sender(string input)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket pub = Helper.GetConnectedPublishSocket(context, Pipe.PublishAddressClient),
                       syncService = context.CreateSocket(SocketType.REP))
                {
                    //syncService.Connect(Pipe.PubSubControlFrontAddressClient);
                    //for (int i = 0; i < 1; i++)
                    //{
                    //    syncService.Receive(Encoding.Unicode);
                    //    syncService.Send("", Encoding.Unicode);
                    //}

                    for (int i = 0; i < 100000; i++)
                    {
                        Console.WriteLine("Enter to send message=>");
                        input = Console.ReadLine();
                        SendMessage(Pipe.ControlChannelEncoding.GetBytes(Pipe.SubscriberCountAddress), Pipe.ControlChannelEncoding.GetBytes("ADDSUBSCRIBER"), pub);
                        if (input == "Exit")
                        {
                            break;
                        }
                        Console.WriteLine("message sent");
                    }

                    Console.WriteLine("message sent enter to exit=>");
                    input = Console.ReadLine();
                }
            }
            return(input);
        }
Esempio n. 26
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket publisher = context.CreateSocket(SocketType.PUB))
                {
                    publisher.Bind("tcp://*:5556");

                    var randomizer = new Random(DateTime.Now.Millisecond);

                    while (true)
                    {
                        //  Get values that will fool the boss
                        int zipcode          = randomizer.Next(0, 100000);
                        int temperature      = randomizer.Next(-80, 135);
                        int relativeHumidity = randomizer.Next(10, 60);

                        string update = zipcode.ToString() + " " + temperature.ToString() + " " + relativeHumidity.ToString();

                        //  Send message to 0..N subscribers via a pub socket
                        publisher.Send(update, Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 27
0
        public void Start()
        {
            try
            {
                using (var context = ZmqContext.Create())
                {
                    using (var socket = context.CreateSocket(SocketType.PULL))
                    {
                        foreach (var bindEndPoint in _bindEndPoints)
                        {
                            socket.Bind(bindEndPoint);
                        }

                        while (true)
                        {
                            var messageFrame = socket.ReceiveFrame();
                            var request      = SerializationMethods.FromByteArray <T>(messageFrame.Buffer);
                            _process(request);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 28
0
        public Subscriber(string _guid, string _targetGuid, string _host, int _port, ZmqContext _ctx)
        {
            guid = _guid;
            targetGuid = _targetGuid;
            host = _host;
            port = _port;
            if (port > 0)
                connectionString = String.Format("tcp://{0}:{1}", host, port);
            else
                connectionString = String.Format("inproc://{0}", targetGuid.ToLower());
            buf = new byte[1024 * 1024];
            subscribeChannels = new List<string>();

            if (_ctx == null)
            {
                shardedCtx = false;
                ctx = ZmqContext.Create();
            }
            else
            {
                shardedCtx = true;
                ctx = _ctx;
            }
            socket = ctx.CreateSocket(SocketType.SUB);
            if (log.IsDebugEnabled) log.DebugFormat("Subscriber connecting to: `{0}`", connectionString);
            socket.Subscribe(Proxy.StringToByteArray(guid));
            socket.Connect(connectionString);
            socket.ReceiveHighWatermark = 1000000;
            socket.ReceiveBufferSize = 128 * 1024;

            lastActiveTime = Proxy.Unixtimestamp();
            log.InfoFormat("Connected successfuly to: `{0}` `{1}`", connectionString, targetGuid);
        }
Esempio n. 29
0
        public static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), controller = context.CreateSocket(SocketType.PUB))
                {
                    receiver.Bind("tcp://*:5558");
                    controller.Bind("tcp://*:5559");

                    //  Wait for start of batch
                    receiver.Receive(Encoding.Unicode);

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

                    const int tasksToConfirm = 100;
                    for (int taskNumber = 0; taskNumber < tasksToConfirm; taskNumber++)
                    {
                        string message = receiver.Receive(Encoding.Unicode);
                        Console.WriteLine(taskNumber % 10 == 0 ? ":" : ".");
                    }

                    stopwatch.Stop();
                    Console.WriteLine("Total elapsed time: {0}", stopwatch.ElapsedMilliseconds);

                    controller.Send("KILL", Encoding.Unicode);
                }
            }
        }
Esempio n. 30
0
        public void Start()
        {
            var zmqVersion = ZmqUtil.GetVersion();

            _logger.InfoFormat("Loaded ZMQ v{0}", zmqVersion.ToString(3));

            if (zmqVersion.Major != 4)
            {
                throw new InvalidOperationException($"Expected ZMQ v4.*, loaded ZMQ v{zmqVersion.ToString(3)}");
            }

            _isListening = true;

            _outboundSockets       = new ConcurrentDictionary <PeerId, ZmqOutboundSocket>();
            _outboundSocketActions = new BlockingCollection <OutboundSocketAction>();
            _pendingDisconnects    = new BlockingCollection <PendingDisconnect>();
            _context = new ZmqContext();

            var startSequenceState = new InboundProcStartSequenceState();

            _inboundThread    = BackgroundThread.Start(InboundProc, startSequenceState);
            _outboundThread   = BackgroundThread.Start(OutboundProc);
            _disconnectThread = BackgroundThread.Start(DisconnectProc);

            startSequenceState.Wait();
            _isRunning = true;
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            //  Prepare our context
            using (ZmqContext context = ZmqContext.Create())
            {
                //  Sockets to send and receive messages on
                using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL),
                       sender = context.CreateSocket(SocketType.PUSH)) {
                    receiver.Connect("tcp://localhost:5557");
                    sender.Connect("tcp://localhost:5558");

                    //  Process tasks forever
                    while (true)
                    {
                        string message = receiver.Receive(Encoding.Unicode);
                        //  Simple progress indicator for the viewer
                        Console.Clear();
                        Console.WriteLine("{0}.", message);

                        //  Do the work
                        Thread.Sleep(Convert.ToInt32(message));

                        //  Send results to sink
                        sender.Send("", Encoding.Unicode);
                    }
                }
            }
        }
Esempio n. 32
0
        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 = ZmqContext.Create())
            {
                using (var socket = context.CreateSocket(SocketType.REP))
                {
                    foreach (var bindEndPoint in options.bindEndPoints)
                    {
                        socket.Bind(bindEndPoint);
                    }
                    while (true)
                    {
                        Thread.Sleep(options.delay);
                        var rcvdMsg = socket.Receive(Encoding.UTF8);
                        Console.WriteLine("Received: " + rcvdMsg);
                        var replyMsg = options.replyMessage.Replace("#msg#", rcvdMsg);
                        Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);
                        socket.Send(replyMsg, Encoding.UTF8);
                    }
                }
            }
        }
Esempio n. 33
0
        public Broker(CancellationToken token, ZmqContext ctx)
        {
            _token = token;
            var ready = new TaskCompletionSource <bool>();

            Task.Factory.StartNew(() => start(ctx, ready));
        }
Esempio n. 34
0
        public void Start()
        {
            subThread         = new BackgroundWorker();
            subThread.DoWork += new DoWorkEventHandler(subThread_DoWork);
            subThread.RunWorkerAsync();

            using (var ctx = ZmqContext.Create())
            {
                using (var socket = ctx.CreateSocket(SocketType.PUB))
                {
                    socket.Bind("tcp://127.0.0.1:5000");
                    while (true)
                    {
                        Thread.Sleep(1000);
                        // Create a ZmqMessage containing 3 frames
                        ZmqMessage zmqMessage = new ZmqMessage();
                        zmqMessage.Append(new Frame(Encoding.UTF8.GetBytes("My Frame 01")));
                        zmqMessage.Append(new Frame(Encoding.UTF8.GetBytes("My Frame 02")));
                        zmqMessage.Append(new Frame(Encoding.UTF8.GetBytes("My Frame 03")));
                        Console.WriteLine("PUB; publishing: ");
                        foreach (var msg in zmqMessage)
                        {
                            Console.WriteLine("\t" + Encoding.UTF8.GetString(msg));
                        }
                        socket.SendMessage(zmqMessage);
                    }
                }
            }
        }
Esempio n. 35
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));
            }
        }
Esempio n. 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ForwarderDevice"/> class.
 /// </summary>
 /// <param name="context">The <see cref="ZmqContext"/> to use when creating the sockets.</param>
 /// <param name="frontendBindAddr">The address used to bind the frontend socket.</param>
 /// <param name="backendBindAddr">The endpoint used to bind the backend socket.</param>
 /// <param name="mode">The <see cref="DeviceMode"/> for the current device.</param>
 public XForwarderDevice(ZmqContext context, string frontendBindAddr, string backendBindAddr, DeviceMode mode)
     : this(context, mode)
 {
     FrontendSetup.Bind(frontendBindAddr);
     FrontendSetup.SubscribeAll();
     BackendSetup.Bind(backendBindAddr);
 }
Esempio n. 37
0
 public ClientForm()
 {
     InitializeComponent();
     context = ZmqContext.Create();
     client = context.CreateSocket(SocketType.REQ);
     client.Connect("tcp://localhost:5555");
 }
Esempio n. 38
0
        public MessageReceiver(ZmqContext context)
        {
            m_Context = context;

            m_Lock = new object();

            m_MessageThread = new Thread(SubscribeAndWait);
        }
Esempio n. 39
0
 public Server(string id, CancellationToken token, ZmqContext ctx)
 {
     _id = id;
     _token = token;
     var ready = new TaskCompletionSource<bool>();
     Task.Factory.StartNew(() => start(ctx, ready));
     ready.Task.Wait();
 }
		public ZeroMqMessagePublisher(ZmqContext context)
		{
			Console.WriteLine("Hey there");
			_pub = context.CreateSocket(SocketType.PUB);
			_pub.Bind("tcp://*:5555");

			Console.WriteLine("Hello");
		}
Esempio n. 41
0
 public ZmqInboundSocket(ZmqContext context, PeerId peerId, ZmqEndPoint originalEndpoint, IZmqSocketOptions options, string environment)
 {
     _context = context;
     _peerId = peerId;
     _originalEndpoint = originalEndpoint;
     _options = options;
     _environment = environment;
 }
Esempio n. 42
0
        public MessageSender(ZmqContext context)
        {
            m_Context = context;
            m_MessageBuffer = new ConcurrentQueue<string>();

            m_MessageThread = new Thread(OnThreadStarted);
            m_MessageThread.Start();
        }
Esempio n. 43
0
        public ZmqSubscriber(string endpoint)
        {
            _endpoint = endpoint;
            _context = ZmqContext.Create();

            BufferSize = 1024;
            ConnectSocket();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ZmqMessageServer"/> class.
        /// </summary>
        /// <param name="messageReceiver">The message receiver.</param>
        /// <param name="port">The port.</param>
        internal ZmqMessageServer(IMessageReceiver messageReceiver, int port)
        {
            tokenSource = new CancellationTokenSource();

            this.port = port;
            this.messageReceiver = messageReceiver;
            context = ZmqContext.Create();
            responseQueue = new ZmqResponseQueue(context, port);
        }
Esempio n. 45
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public MessagingClient()
        {
            // We create the ZMQ context, and a socket to listen to messages...
            m_context = ZmqContext.Create();

            // We start processing messages on a worker thread...
            m_workerThread = new Thread(processMessages);
            m_workerThread.Start();
        }
        //ORDER_CONFIRMATION_TR
        private NNFHandler()
        {
            // MessageBox.Show("Trying Connect to NNF ");
            context = ZmqContext.Create();
            _ctsCancellationTokenSource = new CancellationTokenSource();
            /////////

            /////
        }
Esempio n. 47
0
        public void Start()
        {
            _context = ZmqContext.Create();
            _commandReceiver = _context.CreateSocket(SocketType.REP);
            _commandReceiver.Bind("tcp://*:7777");

            _dequeueReceiver = _context.CreateSocket(SocketType.PUB);
            _dequeueReceiver.Bind("tcp://*:7778");

            StartListener();
        }
Esempio n. 48
0
 private Worker(string address, uint servicePort, string workerId, ZmqContext context = null)
     : base(context)
 {
     _frozen = false;
     _address = address;
     _resolvers = new List<MethodCallResolver>();
     _requestProcessors = new List<IRequestProcessor>();
     _servicePort = servicePort;
     _working = false;
     _workerId = workerId;
 }
Esempio n. 49
0
 public Router(uint frontendPort, uint backendPort, ZmqContext context)
     : base(context)
 {
     _stopCommandToken = Guid.NewGuid().ToString();
     _routing = false;
     // stick on there address first until need for multihomed/bridging the different network
     _backendAddress = "*";
     _frontendAddress = "*";
     _frontendPort = frontendPort;
     _backendPort = backendPort;
 }
Esempio n. 50
0
        private static ZmqSocket CreateServerSocket(ZmqContext context)
        {
            Console.WriteLine("Connecting to server...");

            var client = context.CreateSocket(SocketType.REQ);
            client.Connect(serverEndpoint);
            client.Linger = TimeSpan.Zero;
            client.ReceiveReady += PollInHandler;

            return client;
        }
Esempio n. 51
0
 public void Dispose()
 {
     if (_socket != null)
     {
         _socket.Dispose();
         _socket = null;
     }
     if (_context != null)
     {
         _context.Dispose();
         _context = null;
     }
 }
Esempio n. 52
0
 /// <summary>
 /// Create a new Host Interface server.
 /// </summary>
 /// <param name="port">Port to bind to.</param>
 public HostInterface(int port, INodeController controller)
 {
     log.Info("Host server interface launching...");
     this.port = port;
     context = ZmqContext.Create();
     server = context.CreateSocket(SocketType.ROUTER);
     server.TcpKeepalive = TcpKeepaliveBehaviour.Enable;
     this.controller = controller;
     var controllerPortal = new ControllerPortal();
     controllerPortal.SetNodeID(0);
     controller.Initialize(controllerPortal);
     Instance = this;
 }
Esempio n. 53
0
        public JsonRpcZmqBase(ZmqContext context = null)
        {
            _ownedContext = true;
            _disposed = false;

            if (context != null)
            {
                _context = context;
                _ownedContext = false;
            }

            Active = false;
        }
Esempio n. 54
0
        public GrapevineSender(ZmqContext context, string address, IMessageSerializer serializer)
        {
            _serializer = serializer;
            _scheduler = new EventLoopScheduler();

            _socket = context.CreateSocket(SocketType.PUB);
            _socket.Connect(address);

            _messages = new Subject<ZmqMessage>();
            _messageDispatcher = _messages
                .SubscribeOn(_scheduler)
                .ObserveOn(_scheduler)
                .Subscribe(msg => _socket.SendMessage(msg));
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing && socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            if (disposing && context != null)
            {
                context.Dispose();
                context = null;
            }
        }
Esempio n. 56
0
        public ForwarderService(string frontend, string backend)
        {
            _logger.Info("Creating 0mq context.");
            _context = ZmqContext.Create();
            _logger.Info("done.");

            _logger.Info("Creating 0mq forwarder device.");
            _forwarder = new ForwarderDevice(_context, frontend, backend, DeviceMode.Threaded);
            _logger.Info("done.");

            _logger.Info("Subscribe all on frontend.");
            _forwarder.FrontendSetup.SubscribeAll();
            _logger.Info("done.");
        }
Esempio n. 57
0
        private void doStartServer(ZmqContext context)
        {
            using (var server = context.CreateSocket(SocketType.REP))
            {
                server.Bind("tcp://127.0.0.1:87");

                while (true)
                {
                    var name = server.Receive(Encoding.Unicode);
                    server.Send(DateTime.Now.ToString() + " - " + name, Encoding.Unicode);

                    Console.WriteLine("Processed request from {0}", name);
                }
            }
        }
Esempio n. 58
0
        private void doStartClient(ZmqContext zmqContext, string name)
        {
            using (var client = zmqContext.CreateSocket(SocketType.REQ))
            {
                client.Connect("tcp://127.0.0.1:87");

                while (true)
                {
                    client.Send(name, Encoding.Unicode);
                    var response = client.Receive(Encoding.Unicode);

                    Task.Delay(2000).Wait();
                }
            }
        }
Esempio n. 59
0
        public void Dispose()
        {
            if (Running)
                StopServer();

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
Esempio n. 60
0
        public void Dispose()
        {
            if (!_disposed)
            {
                Stop();

                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }

                GC.SuppressFinalize(this);
                _disposed = true;
            }
        }