Esempio n. 1
0
        static ZFrame FLClient1_TryRequest(ZContext context, string endpoint, ZFrame request)
        {
            Console.WriteLine("I: trying echo service at {0}...", endpoint);

            using (var client = new ZSocket(context, ZSocketType.REQ))
            {
                client.Connect(endpoint);

                // Send request, wait safely for reply
                using (var message = ZFrame.CopyFrom(request))
                {
                    client.Send(message);
                }

                var poll = ZPollItem.CreateReceiver();

                ZError   error;
                ZMessage incoming;

                if (client.PollIn(poll, out incoming, out error, FLClient1_REQUEST_TIMEOUT))
                {
                    return(incoming[0]);
                }
            }
            return(null);
        }
        public void ReceiveReplies(Func <String, MessageType, String, SynapseEndpoint, String, String> callback)
        {
            ZError    error;
            ZMessage  incoming;
            ZPollItem poll = ZPollItem.CreateReceiver();

            while (true)
            {
                if (!Socket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(10)))
                {
                    if (error == ZError.EAGAIN)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    if (error == ZError.ETERM)
                    {
                        return;
                    }
                    throw new ZException(error);
                }
                using (incoming)
                {
                    String      messageId   = incoming[0].ReadString();
                    MessageType messageType = (MessageType)Enum.Parse(typeof(MessageType), incoming[1].ReadString());
                    String      messageText = incoming[2].ReadString();

                    if (callback != null)
                    {
                        callback(messageId, messageType, messageText, this, null);
                    }
                }
            }
        }
Esempio n. 3
0
        public void PollMany_Multiple_InOut()
        {
            using (var context = new ZContext())
            {
                using (var socket1 = new ZSocket(context, ZSocketType.PAIR))
                {
                    socket1.Bind(DefaultEndpoint);
                    using (var socket2 = new ZSocket(context, ZSocketType.PAIR))
                    {
                        socket2.Connect(DefaultEndpoint);

                        var sockets   = new[] { socket1, socket2 };
                        var pollItems = new[] { ZPollItem.CreateSender(), ZPollItem.CreateReceiver() };

                        ZMessage[] messages = new[] { new ZMessage(new[] { new ZFrame(32) }), null };
                        ZError     error;

                        // TODO: why does this return false?
                        Assert.IsTrue(sockets.Poll(pollItems, ZPoll.In | ZPoll.Out, ref messages, out error));
                        Assert.IsNull(error);

                        if (messages[1] == null)
                        {
                            Assert.IsTrue(sockets.Poll(pollItems, ZPoll.In | ZPoll.Out, ref messages, out error));
                            Assert.IsNull(error);
                        }

                        CollectionAssert.AreEqual(new[] { null, new ZMessage(new[] { new ZFrame(32) }) }, messages);
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 代理模式
        /// </summary>
        /// <param name="args"></param>
        public static void RRBroker(ZContext ctx)
        {
            using (var frontend = new ZSocket(ctx, ZSocketType.ROUTER))
                using (var backend = new ZSocket(ctx, ZSocketType.DEALER))
                {
                    frontend.Bind("tcp://*:5559");
                    backend.Bind("tcp://*:5560");

                    // Initialize poll set
                    var poll = ZPollItem.CreateReceiver();

                    // Switch messages between sockets
                    ZError   error;
                    ZMessage message;
                    int      num = 0;
                    while (true)
                    {
                        if (num > 100)
                        {
                            break;
                        }
                        if (frontend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            // Process all parts of the message
                            Console.WriteLine("frontend", 2, message);
                            backend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        if (backend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            // Process all parts of the message
                            Console.WriteLine(" backend", 2, message);
                            frontend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }
                        num++;
                    }
                }
        }
Esempio n. 5
0
        public void PollMany_Single_In_Ready()
        {
            using (var context = new ZContext())
            {
                using (var socket1 = new ZSocket(context, ZSocketType.PAIR))
                {
                    socket1.Bind(DefaultEndpoint);
                    using (var socket2 = new ZSocket(context, ZSocketType.PAIR))
                    {
                        socket2.Connect(DefaultEndpoint);
                        socket2.Send(new ZMessage(new[] { new ZFrame(32) }));

                        var sockets   = new[] { socket1 };
                        var pollItems = new[] { ZPollItem.CreateReceiver() };

                        ZMessage[] messages = null;
                        ZError     error;
                        Assert.IsTrue(sockets.Poll(pollItems, ZPoll.In, ref messages, out error, TimeSpan.Zero));

                        CollectionAssert.AreEqual(new[] { new ZMessage(new[] { new ZFrame(32) }) }, messages);
                        Assert.IsNull(error);
                    }
                }
            }
        }
Esempio n. 6
0
        void MainLoop(object obj)
        {
            using (var outgoing = new ZFrame("READY"))
            {
                workerSocket.Send(outgoing);
            }

            ZError   error;
            ZMessage incoming;
            var      poll = ZPollItem.CreateReceiver();

            while (true)
            {
                while (true)
                {
                    var result = workerSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(1));
                    if (!result)
                    {
                        if (error == ZError.EAGAIN)
                        {
                            //await Task.Delay(1);
                            //yield return null;
                            continue;
                        }
                        if (error == ZError.ETERM)
                        {
                            Logger.Error("ETERM!");
                            return; // Interrupted
                            //yield break;
                        }
                        throw new ZException(error);
                    }
                    else
                    {
                        using (incoming)
                        {
                            // Send message back
                            //worker.Send(incoming);
                            _server.OnRecvMsg(this, incoming);
                            break;
                        }
                    }
                }
                //if (null == (incoming = workerSocket.ReceiveMessage(out error)))
                //{
                //    if (error == ZError.ETERM)
                //        return;

                //    throw new ZException(error);
                //}

                //using (incoming)
                //{
                //    // Send message back
                //    //worker.Send(incoming);
                //    _server.OnRecvMsg(this, incoming);

                //}
            }
        }
Esempio n. 7
0
        static void PubSub_Client(CancellationToken cancellus, string name)
        {
            using (var socket = ZSocket.Create(context, ZSocketType.SUB))
            {
                socket.Connect(Frontend);

                socket.SubscribeAll();

                ZError   error;
                ZMessage message;
                var      poller = ZPollItem.CreateReceiver();

                while (!cancellus.IsCancellationRequested)
                {
                    if (!socket.PollIn(poller, out message, out error, TimeSpan.FromMilliseconds(64)))
                    {
                        if (error == ZError.EAGAIN)
                        {
                            error = ZError.None;
                            Thread.Sleep(1);

                            continue;
                        }
                        throw new ZException(error);
                    }

                    using (message)
                    {
                        Console.WriteLine(name + " received " + message[0].ReadString());
                    }
                }

                socket.Disconnect(Frontend);
            }
        }
Esempio n. 8
0
 public ZmqRequester(ZmqContext context)
 {
     socket  = new ZSocket(context.Context, ZSocketType.REQ);
     poll    = ZPollItem.CreateReceiver();
     isSet   = false;
     isStart = false;
 }
Esempio n. 9
0
        protected MonitoredSocketUser(String monitorAddress, ZSocketType socketType, TimeSpan pollWaitTime)
        {
            m_context = new ZContext();
            m_socket  = new ZSocket(m_context, socketType)
            {
                Linger = ZMQLinger,
                ReceiveHighWatermark = RCVHWM,
                SendHighWatermark    = SNDHWM
            };
            m_socket.Monitor(monitorAddress);
            m_monitor            = ZMonitor.Create(m_context, monitorAddress);
            m_poller             = ZPollItem.CreateReceiver();
            m_monitor.AllEvents += (sender, e) =>
                                   ScreenLogger.Log(
                ((Int32)e.Event.Event is 4096) ?
                $"Event fired on socket {e.Event.Address}: Handshake Success" :
                $"Event fired on socket {e.Event.Address}: {e.Event.Event}",
                LogObject.EventManager);
            m_cancelCondition = true;

            m_receiveBuffer = new BufferBlock <ZMessage>();
            m_sendAction    = new ActionBlock <ZMessage>((msg) => { m_socket.Send(msg); msg.Dispose(); });

            m_pollWaitTime = MinPollWaitTime;
            if (pollWaitTime > m_pollWaitTime)
            {
                m_pollWaitTime = pollWaitTime;
            }

            ListenLoop();
        }
Esempio n. 10
0
        public void StartRouterDealer()
        {
            using (var frontend = new ZSocket(context, ZSocketType.ROUTER))
                using (var backend = new ZSocket(context, ZSocketType.DEALER))
                {
                    var frontEndUrl   = string.Format("tcp://{0}:{1}", MessageBusConfig.Hostname, MessageBusConfig.PortNumberRouter);
                    var backendEndUrl = string.Format("tcp://{0}:{1}", MessageBusConfig.Hostname, MessageBusConfig.PortNumberDealer);

                    frontend.Bind(frontEndUrl);
                    backend.Bind(backendEndUrl);

                    var poll = ZPollItem.CreateReceiver();

                    // Switch messages between sockets
                    ZError   error;
                    ZMessage message;

                    RaiseOnRouterDealerReady();

                    while (true)
                    {
                        if (frontend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            RaiseOnRouterMessageReceived(message);
                            // Process all parts of the message
                            backend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        if (backend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            RaiseOnDealerMessageReceived(message);
                            // Process all parts of the message
                            frontend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }
                    }
                }
        }
Esempio n. 11
0
            //  .skip
            //  The recv method waits for a reply message and returns that to the
            //  caller.
            //  ---------------------------------------------------------------------
            //  Returns the reply message or NULL if there was no reply. Does not
            //  attempt to recover from a broker failure, this is not possible
            //  without storing all unanswered requests and resending them all...
            public ZMessage Recv(CancellationTokenSource cancellor)
            {
                //  Poll socket for a reply, with timeout
                var      p = ZPollItem.CreateReceiver();
                ZMessage msg;
                ZError   error;

                //  .split body of send
                //  On any blocking call, {{libzmq}} will return -1 if there was
                //  an error; we could in theory check for different error codes,
                //  but in practice it's OK to assume it was {{EINTR}} (Ctrl-C):

                // Poll the client Message
                if (Client.PollIn(p, out msg, out error, Timeout))
                {
                    //  If we got a reply, process it
                    if (Verbose)
                    {
                        msg.DumpZmsg("I: received reply");
                    }

                    //  Don't try to handle errors, just assert noisily
                    if (msg.Count < 4)
                    {
                        throw new InvalidOperationException();
                    }

                    using (ZFrame empty = msg.Pop())
                        if (!empty.ToString().Equals(string.Empty))
                        {
                            throw new InvalidOperationException();
                        }

                    using (ZFrame header = msg.Pop())
                        if (!header.ToString().Equals(MdpCommon.MDPC_CLIENT))
                        {
                            throw new InvalidOperationException();
                        }

                    using (ZFrame replyService = msg.Pop())
                    {}

                    return(msg);
                }
                else if (Equals(error, ZError.ETERM))
                {
                    "W: interrupt received, killing client...\n".DumpString();
                    cancellor.Cancel();
                }
                else
                {
                    if (Verbose)
                    {
                        "W: permanent error, abandoning Error: {0}".DumpString(error);
                    }
                }

                return(null);
            }
Esempio n. 12
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);
                            }
                        }
                    }
            }
        }
        protected MonitoredDoubleSocketUser(String tcpMonitorAddress,
                                            String udpMonitorAddress,
                                            ZSocketType socketType,
                                            TimeSpan pollWaitTime)
        {
            m_context = new ZContext();

            m_tcpSocket = new ZSocket(m_context, socketType)
            {
                Linger = ZMQLinger,
                ReceiveHighWatermark = RCVHWM,
                SendHighWatermark    = SNDHWM
            };
            m_tcpSocket.Monitor(tcpMonitorAddress);
            m_tcpSocketMonitor            = ZMonitor.Create(m_context, tcpMonitorAddress);
            m_poller                      = ZPollItem.CreateReceiver();
            m_tcpSocketMonitor.AllEvents += (sender, e) =>
                                            ScreenLogger.Log(
                ((Int32)e.Event.Event is 4096) ?
                $"Event fired on main TCP socket: Handshake Success" :
                $"Event fired on main TCP socket: {e.Event.Event}",
                LogObject.EventManager);

            /*
             * m_udpSocket = new ZSocket(m_context, socketType)
             * {
             *  Linger = ZMQLinger,
             *  ReceiveHighWatermark = RCVHWM,
             *  SendHighWatermark = SNDHWM
             * };
             * m_udpSocket.Monitor(udpMonitorAddress);
             * m_udpSocketMonitor = ZMonitor.Create(m_context, udpMonitorAddress);
             * m_poller = ZPollItem.CreateReceiver();
             * m_udpSocketMonitor.AllEvents += (sender, e) =>
             *  ScreenLogger.Log(
             *          ((Int32)e.Event.Event is 4096) ?
             *          $"Event fired on main UDP socket: Handshake Success" :
             *          $"Event fired on main UDP socket: {e.Event.Event}",
             *      LogObject.EventManager);
             */

            m_cancelConddition = true;

            m_receiveBuffer       = new BufferBlock <(TransportProtocol, ZMessage)>();
            m_tcpSocketSendAction = new ActionBlock <ZMessage>((msg) => { m_tcpSocket.Send(msg); msg.Dispose(); });
            //m_udpSocketSendAction = new ActionBlock<ZMessage>((msg) => { m_udpSocket.Send(msg); msg.Dispose(); });

            m_pollWaitTime = MinPollWaitTime;
            if (pollWaitTime > m_pollWaitTime)
            {
                m_pollWaitTime = pollWaitTime;
            }

            ListenLoop();
        }
Esempio n. 14
0
        public void Run()
        {
            //using (var ctx = new ZContext())
            using (var frontend = new ZSocket(ZSocketType.ROUTER))
                using (var backend = new ZSocket(ZSocketType.DEALER))
                {
                    frontend.Bind("tcp://*:5559");
                    backend.Bind("tcp://*:5560");

                    // Initialize poll set
                    var poll = ZPollItem.CreateReceiver();

                    // Switch messages between sockets
                    ZError   error;
                    ZMessage message;
                    while (true)
                    {
                        if (frontend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            // Process all parts of the message
                            //Console_WriteZMessage("frontend", 2, message);
                            backend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        if (backend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            // Process all parts of the message
                            //Console_WriteZMessage(" backend", 2, message);
                            frontend.Send(message);
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }
                    }
                }
        }
Esempio n. 15
0
        /// <summary>
        /// Client
        /// </summary>
        /// <param name="context"></param>
        /// <param name="i"></param>
        private static void AsyncSrv_Client(ZContext context, int i)
        {
            using (var client = new ZSocket(context, ZSocketType.DEALER))
            {
                client.Identity = Encoding.UTF8.GetBytes("Client" + i);
                client.Connect("tcp://127.0.0.1:5570");
                var poll     = ZPollItem.CreateReceiver();
                var requests = 0;
                while (true)
                {
                    ZError error;
                    for (var centitick = 0; centitick < 100; ++centitick)
                    {
                        if (!client.PollIn(poll, out var incoming, out error, TimeSpan.FromMilliseconds(10)))
                        {
                            if (Equals(error, ZError.EAGAIN))
                            {
                                Thread.Sleep(1);
                                continue;
                            }
                            if (Equals(error, ZError.ETERM))
                            {
                                continue;                                // Interrupted
                            }
                            throw new ZException(error);
                        }
                        using (incoming)
                        {
                            Console.WriteLine("--------------client-----------------");
                            for (var j = 0; j < incoming.Count; j++)
                            {
                                Console.WriteLine($"    {j}:{incoming[j].ReadString()}");
                            }
                            Console.WriteLine("--------------client-----------------");
                        }
                    }
                    using (var outgoing = new ZMessage())
                    {
                        outgoing.Add(new ZFrame("c-xxx"));
                        outgoing.Add(new ZFrame("request " + (++requests)));

                        if (client.Send(outgoing, out error))
                        {
                            continue;
                        }
                        if (Equals(error, ZError.ETERM))
                        {
                            return;                                // Interrupted
                        }
                        throw new ZException(error);
                    }
                }
            }
        }
Esempio n. 16
0
        public static void MSPoller(string[] args)
        {
            //
            // Reading from multiple sockets
            // This version uses zmq_poll()
            //
            // Author: metadings
            //

            using (var context = new ZContext())
                using (var receiver = new ZSocket(context, ZSocketType.PULL))
                    using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                    {
                        // Connect to task ventilator
                        receiver.Connect("tcp://127.0.0.1:5557");

                        // Connect to weather server
                        subscriber.Connect("tcp://127.0.0.1:5556");
                        subscriber.SetOption(ZSocketOption.SUBSCRIBE, "10001 ");

                        var sockets = new ZSocket[] { receiver, subscriber };
                        var polls   = new ZPollItem[] { ZPollItem.CreateReceiver(), ZPollItem.CreateReceiver() };

                        // Process messages from both sockets
                        ZError     error;
                        ZMessage[] msg;
                        while (true)
                        {
                            if (sockets.PollIn(polls, out msg, out error, TimeSpan.FromMilliseconds(64)))
                            {
                                if (msg[0] != null)
                                {
                                    // Process task
                                }
                                if (msg[1] != null)
                                {
                                    // Process weather update
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;                     // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }
                        }
                    }
        }
Esempio n. 17
0
        // private static readonly int sizeof_MonitorEventData = Marshal.SizeOf(typeof(ZMonitorEventData));

        /// <summary>
        /// Begins monitoring for state changes, raising the appropriate events as they arrive.
        /// </summary>
        /// <remarks>NOTE: This is a blocking method and should be run from another thread.</remarks>
        protected override void Run()
        {
            using (_socket)
            {
                ZError error;
                if (!_socket.Connect(_endpoint, out error))
                {
                    LogError(error, "connect");
                    return;
                }

                var poller = ZPollItem.CreateReceiver();

                while (!Cancellor.IsCancellationRequested)
                {
                    ZMessage incoming;
                    if (!_socket.PollIn(poller, out incoming, out error, PollingInterval))
                    {
                        if (error == ZError.EAGAIN)
                        {
                            // TODO: why sleep here? the loop frequency is already controlled by PollingInterval
                            Thread.Sleep(1);
                            continue;
                        }

                        LogError(error, "poll");
                    }

                    var eventValue = new ZMonitorEventData();

                    using (incoming)
                    {
                        if (incoming.Count > 0)
                        {
                            eventValue.Event      = (ZMonitorEvents)incoming[0].ReadInt16();
                            eventValue.EventValue = incoming[0].ReadInt32();
                        }

                        if (incoming.Count > 1)
                        {
                            eventValue.Address = incoming[1].ReadString();
                        }
                    }

                    OnMonitor(eventValue);
                }

                if (!_socket.Disconnect(_endpoint, out error))
                {
                    LogError(error, "disconnect");
                }
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            //
            // Task worker - design 2
            // Adds pub-sub flow to receive and respond to kill signal
            //
            // Author: metadings
            //

            // Socket to receive messages on,
            // Socket to send messages to and
            // Socket for control input
            using (var context = new ZContext())
                using (var receiver = new ZSocket(context, ZSocketType.PULL))
                    using (var sender = new ZSocket(context, ZSocketType.PUSH))
                        using (var controller = new ZSocket(context, ZSocketType.SUB))
                        {
                            receiver.Connect("tcp://127.0.0.1:5557");
                            sender.Connect("tcp://127.0.0.1:5558");

                            controller.Connect("tcp://127.0.0.1:5559");
                            controller.SubscribeAll();

                            var poll = ZPollItem.CreateReceiver();

                            ZError   error;
                            ZMessage message;

                            while (true)
                            {
                                // Process messages from either socket
                                if (receiver.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                                {
                                    int workload = message[0].ReadInt32();
                                    Console.WriteLine("{0}.", workload); // Show progress

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

                                    sender.Send(new byte[0], 0, 0);      // Send results to sink
                                }

                                //Console.WriteLine("Any waiting controller command acts as 'KILL'");
                                // Any waiting controller command acts as 'KILL'
                                if (controller.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                                {
                                    Console.WriteLine("Kill messsage received");
                                    break; // Exit loop
                                }
                            }
                        }
        }
Esempio n. 19
0
        private void MonitorChannels()
        {
            var      poll = ZPollItem.CreateReceiver();
            ZMessage incoming;
            ZError   error;

            while (!_monitorChannnelsCts.IsCancellationRequested)
            {
                if (_monitorChannnelsCts.IsCancellationRequested)
                {
                    break;
                }

                if (StdInSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                {
                    break;
                }

                if (IoPubSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                {
                    break;
                }

                if (ShellSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (_monitorChannnelsCts.IsCancellationRequested)
                {
                    break;
                }

                if (ControlSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }
            }
            ContinueShutdown.Set();
        }
Esempio n. 20
0
 protected virtual bool Initialize(string endpoint, ZSocketType type, Action <ZSocket> modifySocketCallback)
 {
     // Disable ZMQ for non-windows platforms.
     if (Application.platform != RuntimePlatform.WindowsEditor &&
         Application.platform != RuntimePlatform.WindowsPlayer)
     {
         Debug.LogWarning($"ZMQ Connection is not supported on this platform. {nameof(ZeroMQHandler)} will be disabled.");
         return(false);
     }
     Poller = ZPollItem.CreateReceiver();
     Socket = new ZSocket(type);
     modifySocketCallback(Socket);
     return(true);
 }
Esempio n. 21
0
        internal Jomiel(Options opts)
        {
            _ctx    = new ZContext();
            _sck    = new ZSocket(_ctx, ZSocketType.REQ);
            _poller = ZPollItem.CreateReceiver();

            _jsonSettings = new JsonSerializerSettings {
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver     = new DynamicContractResolver(),
            };

            _sck.Linger = TimeSpan.FromMilliseconds(0);
            _opts       = opts;
        }
        public static void Start()
        {
            using (var ctx = new ZContext())
                using (var frontend = new ZSocket(ctx, ZSocketType.ROUTER))
                    using (var backend = new ZSocket(ctx, ZSocketType.DEALER))
                    {
                        frontend.Bind("tcp://*:8081");
                        backend.Bind("tcp://*:8082");

                        var poll = ZPollItem.CreateReceiver();

                        while (true)
                        {
                            ZError   error;
                            ZMessage message;

                            if (frontend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                            {
                                backend.Send(message);
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            if (backend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                            {
                                frontend.Send(message);
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }
                        }
                    }
        }
Esempio n. 23
0
        public void PollInSingle_Timeout()
        {
            using (var context = new ZContext())
            {
                using (var socket = new ZSocket(context, ZSocketType.PAIR))
                {
                    ZMessage message;
                    ZError   error;
                    Assert.IsFalse(socket.PollIn(ZPollItem.CreateReceiver(), out message, out error, TimeSpan.Zero));

                    Assert.IsNull(message);
                    Assert.AreEqual(ZError.EAGAIN, error);
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 代理2
        /// </summary>
        /// <param name="context"></param>
        public static void RRBroker(ZContext context)
        {
            using (var ctx = new ZContext())
                using (var frontend = new ZSocket(ctx, ZSocketType.ROUTER))
                    using (var backend = new ZSocket(ctx, ZSocketType.DEALER))
                    {
                        frontend.Bind("tcp://*:5570");
                        backend.Bind("inproc://backend");
                        Thread.Sleep(2000);
                        //backend.SendFrame(new ZFrame("hahah"));

                        var poll = ZPollItem.CreateReceiver();
                        while (true)
                        {
                            if (frontend.PollIn(poll, out var message, out var error, TimeSpan.FromMilliseconds(64)))
                            {
                                backend.Send(message);
                            }
Esempio n. 25
0
        public void PollMany_Single_Timeout()
        {
            using (var context = new ZContext())
            {
                using (var socket = new ZSocket(context, ZSocketType.PAIR))
                {
                    var sockets   = new[] { socket };
                    var pollItems = new[] { ZPollItem.CreateReceiver() };

                    ZMessage[] messages = null;
                    ZError     error;
                    Assert.IsFalse(sockets.Poll(pollItems, ZPoll.In, ref messages, out error, TimeSpan.Zero));

                    CollectionAssert.AreEqual(new ZMessage[] { null }, messages);
                    Assert.AreEqual(ZError.EAGAIN, error);
                }
            }
        }
Esempio n. 26
0
        // private static readonly int sizeof_MonitorEventData = Marshal.SizeOf(typeof(ZMonitorEventData));

        /// <summary>
        /// Begins monitoring for state changes, raising the appropriate events as they arrive.
        /// </summary>
        /// <remarks>NOTE: This is a blocking method and should be run from another thread.</remarks>
        protected override void Run()
        {
            _socket.Connect(_endpoint);

            ZError   error;
            ZMessage incoming;
            var      poller = ZPollItem.CreateReceiver();

            while (!Cancellor.IsCancellationRequested)
            {
                if (!_socket.PollIn(poller, out incoming, out error, PollingInterval))
                {
                    if (error == ZError.EAGAIN)
                    {
                        Thread.Sleep(1);
                        continue;
                    }

                    throw new ZException(error);
                }

                var eventValue = new ZMonitorEventData();

                using (incoming) {
                    if (incoming.Count > 0)
                    {
                        eventValue.Event      = (ZMonitorEvents)incoming[0].ReadInt16();
                        eventValue.EventValue = incoming[0].ReadInt32();
                    }

                    if (incoming.Count > 1)
                    {
                        eventValue.Address = incoming[1].ReadString();
                    }
                }

                OnMonitor(eventValue);
            }

            if (!_socket.Disconnect(_endpoint, out error))
            {
            }                                                              // ignore errors
        }
Esempio n. 27
0
        public void PollInSingle_CancelByContextClose()
        {
            Task   task;
            ZError error = null;

            using (var context = new ZContext())
            {
                var socket = new ZSocket(context, ZSocketType.PAIR);
                task = Task.Run(() =>
                {
                    using (socket)
                    {
                        ZMessage message;

                        socket.PollIn(ZPollItem.CreateReceiver(), out message, out error);
                    }
                });
            }
            Assert.IsTrue(task.Wait(1000));
            Assert.AreEqual(ZError.ETERM, error);
        }
Esempio n. 28
0
        public JupyterMessage Execute(string code)
        {
            FlushMessages();
            CurrentState = KernelState.busy;
            SendShell(
                JupyterMessage.Header.MsgType.execute_request,
                new JupyterMessage.ExecuteRequestContent
            {
                code             = code,
                silent           = false,
                store_history    = true,
                user_expressions = null,
                allow_stdin      = true,
                stop_on_error    = false
            },
                null);

            var      poll = ZPollItem.CreateReceiver();
            ZMessage incoming;
            ZError   error;

            while (CurrentState != KernelState.idle)
            {
                if (StdInSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }

                if (IoPubSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(100)))
                {
                    ProcessMessage(incoming, error);
                }
            }

            var replyMessage = ShellSocket.ReceiveMessage();

            return(ParseMessage(replyMessage));
        }
Esempio n. 29
0
        /// <summary>
        /// 接收完关闭模式
        /// </summary>
        /// <param name="args"></param>
        public static void TaskWork2(string[] args)
        {
            using (var context = new ZContext())
                using (var receiver = new ZSocket(context, ZSocketType.PULL))
                    using (var sender = new ZSocket(context, ZSocketType.PUSH))
                        using (var controller = new ZSocket(context, ZSocketType.SUB))
                        {
                            receiver.Connect("tcp://127.0.0.1:5557");
                            sender.Connect("tcp://127.0.0.1:5558");

                            controller.Connect("tcp://127.0.0.1:5559");
                            controller.SubscribeAll();

                            var poll = ZPollItem.CreateReceiver();

                            ZError   error;
                            ZMessage message;
                            while (true)
                            {
                                // Process messages from either socket
                                if (receiver.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                                {
                                    int workload = message[0].ReadInt32();
                                    Console.WriteLine("{0}.", workload); // Show progress

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

                                    sender.Send(new byte[0], 0, 0);      // Send results to sink
                                }

                                // Any waiting controller command acts as 'KILL'
                                if (controller.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64)))
                                {
                                    break; // Exit loop
                                }
                            }
                        }
        }
Esempio n. 30
0
        public void PollInMany_CancelByContextClose()
        {
            Task   task;
            ZError error = null;

            using (var context = new ZContext())
            {
                var socket = new ZSocket(context, ZSocketType.PAIR);
                task = Task.Run(() =>
                {
                    using (socket)
                    {
                        var sockets   = new[] { socket };
                        var pollItems = new[] { ZPollItem.CreateReceiver() };

                        ZMessage[] messages;
                        sockets.PollIn(pollItems, out messages, out error, TimeSpan.Zero);
                    }
                });
            }
            Assert.IsTrue(task.Wait(1000));
            Assert.AreEqual(ZError.ETERM, error);
        }