Ejemplo n.º 1
0
        public NetMQScheduler(NetMQContext context, Poller poller = null)
        {
            m_context = context;
            if (poller == null)
            {
                m_ownPoller = true;

                m_poller = new Poller();
            }
            else
            {
                m_ownPoller = false;

                m_poller = poller;
            }

            m_clientSockets = new ConcurrentBag <NetMQSocket>();

            m_schedulerId = Interlocked.Increment(ref s_schedulerCounter);

            m_address = string.Format("{0}://scheduler-{1}", NetMQ.zmq.Address.InProcProtocol, m_schedulerId);

            m_serverSocket = context.CreatePullSocket();
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(m_address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = new ThreadLocal <NetMQSocket>(() =>
            {
                var socket = m_context.CreatePushSocket();
                socket.Connect(m_address);

                m_clientSockets.Add(socket);

                return(socket);
            });

            m_schedulerThread = new ThreadLocal <bool>(() => false);

            if (m_ownPoller)
            {
                Task.Factory.StartNew(m_poller.Start, TaskCreationOptions.LongRunning);
            }
        }
        public static Task <(string, bool)> ReceiveFrameStringAsync(
            [NotNull] this NetMQSocket socket,
            [NotNull] Encoding encoding,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (NetMQRuntime.Current == null)
            {
                throw new InvalidOperationException("NetMQRuntime must be created before calling async functions");
            }

            socket.AttachToRuntime();

            var msg = new Msg();

            msg.InitEmpty();

            if (socket.TryReceive(ref msg, TimeSpan.Zero))
            {
                var str = msg.Size > 0
                    ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                    : string.Empty;

                msg.Close();
                return(Task.FromResult((str, msg.HasMore)));
            }

            TaskCompletionSource <(string, bool)> source = new TaskCompletionSource <(string, bool)>();

            cancellationToken.Register(() => source.SetCanceled());

            void Listener(object sender, NetMQSocketEventArgs args)
            {
                if (socket.TryReceive(ref msg, TimeSpan.Zero))
                {
                    var str = msg.Size > 0
                        ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                        : string.Empty;
                    bool more = msg.HasMore;

                    msg.Close();
                    socket.ReceiveReady -= Listener;
                    source.SetResult((str, more));
                }
            }

            socket.ReceiveReady += Listener;

            return(source.Task);
        }
Ejemplo n.º 3
0
            public void RunPipeline(Sockets.PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                while (!m_terminated)
                {
                    PollItem[] pollItems = new PollItem[]
                    {
                        new PollItem(m_pipe.SocketHandle, PollEvents.PollIn),
                        new PollItem(m_udpSocket, PollEvents.PollIn),
                    };

                    long timeout = -1;

                    if (m_transmit != null)
                    {
                        timeout = m_pingAt - Clock.NowMs();

                        if (timeout < 0)
                        {
                            timeout = 0;
                        }
                    }

                    ZMQ.Poll(pollItems, m_udpSocket != null ? 2 : 1, (int)timeout);

                    if (pollItems[0].ResultEvent.HasFlag(PollEvents.PollIn))
                    {
                        HandlePipe();
                    }

                    if (pollItems[1].ResultEvent.HasFlag(PollEvents.PollIn))
                    {
                        HandleUdp();
                    }

                    if (m_transmit != null && Clock.NowMs() > m_pingAt)
                    {
                        SendUdpFrame(m_transmit);
                        m_pingAt = Clock.NowMs() + m_interval;
                    }
                }

                m_udpSocket.Dispose();
            }
Ejemplo n.º 4
0
        public void RemoveSocket(NetMQSocket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("stock");
            }

            if (m_disposed)
            {
                throw new ObjectDisposedException("Poller is disposed");
            }

            socket.EventsChanged -= OnSocketEventsChanged;

            m_sockets.Remove(socket);
            m_isDirty = true;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Receive a single frame from <paramref name="socket"/>, asynchronously.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="cancellationToken">The token used to propagate notification that this operation should be canceled.</param>
        /// <returns>The content of the received message frame and boolean indicate if another frame of the same message follows.</returns>
        public static Task <(byte[], bool)> ReceiveFrameBytesAsync(
            this NetMQSocket socket,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            if (NetMQRuntime.Current == null)
            {
                throw new InvalidOperationException("NetMQRuntime must be created before calling async functions");
            }

            socket.AttachToRuntime();

            var msg = new Msg();

            msg.InitEmpty();

            if (socket.TryReceive(ref msg, TimeSpan.Zero))
            {
                var  data = msg.CloneData();
                bool more = msg.HasMore;
                msg.Close();

                return(Task.FromResult((data, more)));
            }

            TaskCompletionSource <(byte[], bool)> source = new TaskCompletionSource <(byte[], bool)>();

            cancellationToken.Register(() => source.SetCanceled());

            void Listener(object sender, NetMQSocketEventArgs args)
            {
                if (socket.TryReceive(ref msg, TimeSpan.Zero))
                {
                    var  data = msg.CloneData();
                    bool more = msg.HasMore;
                    msg.Close();

                    socket.ReceiveReady -= Listener;
                    source.SetResult((data, more));
                }
            }

            socket.ReceiveReady += Listener;

            return(source.Task);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="frontend">the socket that messages will be forwarded from</param>
        /// <param name="backend">the socket that messages will be forwarded to</param>
        /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
        /// <param name="poller">an optional external poller to use within this proxy</param>
        /// <exception cref="InvalidOperationException"><paramref name="poller"/> is not <c>null</c> and either <paramref name="frontend"/> or <paramref name="backend"/> are not contained within it.</exception>
        public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket control = null, Poller poller = null)
        {
            if (poller != null)
            {
                if (!poller.ContainsSocket(backend) || !poller.ContainsSocket(frontend))
                {
                    throw new InvalidOperationException("When using an external poller, both the frontend and backend sockets must be added to it.");
                }

                m_externalPoller = true;
                m_poller         = poller;
            }

            m_frontend = frontend;
            m_backend  = backend;
            m_control  = control;
        }
Ejemplo n.º 7
0
        public static Task SendFrameAsync(
            this NetMQSocket socket,
            byte[] data,
            bool more = false,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            if (NetMQRuntime.Current == null)
            {
                throw new InvalidOperationException("NetMQRuntime must be created before calling async functions");
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            socket.AttachToRuntime();

            if (socket.TrySendFrame(TimeSpan.Zero, data, more))
            {
                return(Task.CompletedTask);
            }

            TaskCompletionSource <object> source = new TaskCompletionSource <object>();

            cancellationToken.Register(() =>
            {
                socket.SendReady -= Listener;
                source.TrySetCanceled();
            });

            void Listener(object sender, NetMQSocketEventArgs args)
            {
                if (socket.TrySendFrame(TimeSpan.Zero, data, more))
                {
                    socket.SendReady -= Listener;
                    source.TrySetResult(null);
                }
            }

            socket.SendReady += Listener;

            return(source.Task);
        }
Ejemplo n.º 8
0
        public NetMQScheduler(NetMQContext context, Poller poller = null)
        {
            m_context = context;
            if (poller == null)
            {
                m_ownPoller = true;
                m_poller    = new Poller();
            }
            else
            {
                m_ownPoller = false;
                m_poller    = poller;
            }

            m_tasksQueue = new ConcurrentQueue <Task>();
            m_syncObject = new object();

            m_schedulerId = Interlocked.Increment(ref s_schedulerCounter);

            m_address = string.Format("{0}://scheduler-{1}", NetMQ.zmq.Address.InProcProtocol, m_schedulerId);

            m_serverSocket = context.CreatePullSocket();
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(m_address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = m_context.CreatePushSocket();
            m_clientSocket.Connect(m_address);

            m_schedulerThread = new ThreadLocal <bool>(() => false);

            if (m_ownPoller)
            {
                m_poller.PollTillCancelledNonBlocking();
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Receive a single frame from <paramref name="socket"/>, asynchronously.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="expectedFrameCount">Specifies the initial capacity of the <see cref="List{T}"/> used
        /// to buffer results. If the number of frames is known, set it here. If more frames arrive than expected,
        /// an extra allocation will occur, but the result will still be correct.</param>
        /// <param name="cancellationToken">The token used to propagate notification that this operation should be canceled.</param>
        /// <returns>The content of the received message.</returns>
        public static async Task <NetMQMessage> ReceiveMultipartMessageAsync(
            this NetMQSocket socket,
            int expectedFrameCount = 4,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = new NetMQMessage(expectedFrameCount);

            while (true)
            {
                (byte[] bytes, bool more) = await socket.ReceiveFrameBytesAsync(cancellationToken);

                message.Append(bytes);

                if (!more)
                {
                    break;
                }
            }

            return(message);
        }
Ejemplo n.º 10
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                m_poller = new NetMQPoller {
                    m_pipe, m_pingTimer
                };

                m_poller.Run();

                // the beacon might never been configured
                m_udpSocket?.Close();
            }
Ejemplo n.º 11
0
        public static NetMQMessage ReceiveMessage(this NetMQSocket socket, TimeSpan timeout)
        {
            var item  = new PollItem(socket.SocketHandle, PollEvents.PollIn);
            var items = new[] { item };

            ZMQ.Poll(items, (int)timeout.TotalMilliseconds);

            if (item.ResultEvent.HasFlag(PollEvents.PollError) && !socket.IgnoreErrors)
            {
                throw new ErrorPollingException("Error while polling", socket);
            }

            if (!item.ResultEvent.HasFlag(PollEvents.PollIn))
            {
                return(null);
            }

            var msg = socket.ReceiveMessage();

            return(msg);
        }
        /// <summary>
        /// Receive a single frame from <paramref name="socket"/>, asynchronously, then ignore its content.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <returns>Boolean indicate if another frame of the same message follows</returns>
        public static Task <bool> SkipFrameAsync([NotNull] this NetMQSocket socket)
        {
            if (NetMQRuntime.Current == null)
            {
                throw new InvalidOperationException("NetMQRuntime must be created before calling async functions");
            }

            socket.AttachToRuntime();

            var msg = new Msg();

            msg.InitEmpty();

            if (socket.TryReceive(ref msg, TimeSpan.Zero))
            {
                bool more = msg.HasMore;
                msg.Close();

                return(more ? s_trueTask : s_falseTask);
            }

            TaskCompletionSource <bool> source = new TaskCompletionSource <bool>();

            void Listener(object sender, NetMQSocketEventArgs args)
            {
                if (socket.TryReceive(ref msg, TimeSpan.Zero))
                {
                    bool more = msg.HasMore;
                    msg.Close();
                    socket.ReceiveReady -= Listener;
                    source.SetResult(more);
                }
            }

            socket.ReceiveReady += Listener;

            return(source.Task);
        }
Ejemplo n.º 13
0
        public void AddSocket(NetMQSocket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("stock");
            }

            if (m_sockets.Contains(socket))
            {
                throw new ArgumentException("Socket already added to poller");
            }

            if (m_disposed)
            {
                throw new ObjectDisposedException("Poller is disposed");
            }

            m_sockets.Add(socket);

            socket.EventsChanged += OnSocketEventsChanged;

            m_isDirty = true;
        }
Ejemplo n.º 14
0
        private NetMQScheduler(Poller poller, PushSocket pushSocket, PullSocket pullSocket)
        {
            if (poller == null)
            {
                m_ownPoller = true;
                m_poller    = new Poller();
            }
            else
            {
                m_ownPoller = false;
                m_poller    = poller;
            }

            var address = string.Format("{0}://scheduler-{1}",
                                        Address.InProcProtocol,
                                        Interlocked.Increment(ref s_schedulerCounter));

            m_serverSocket = pullSocket;
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = pushSocket;
            m_clientSocket.Connect(address);

            m_isSchedulerThread = new ThreadLocal <bool>(() => false);

            if (m_ownPoller)
            {
                m_poller.PollTillCancelledNonBlocking();
            }
        }
Ejemplo n.º 15
0
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(0);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                m_poller = new Poller();
                m_poller.AddSocket(m_pipe);
                m_poller.AddTimer(m_pingTimer);

                m_poller.PollTillCancelled();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Close();
                }
            }
        /// <summary>
        /// Runs the poller on the caller's thread. Only returns when <see cref="Stop"/> or <see cref="StopAsync"/> are called from another thread.
        /// </summary>
        private void RunPoller()
        {
            try
            {
                // Recalculate all timers now
                foreach (var timer in m_timers)
                {
                    if (timer.Enable)
                    {
                        timer.When = Clock.NowMs() + timer.Interval;
                    }
                }

                // Run until stop is requested
                while (!m_stopSignaler.IsStopRequested)
                {
                    if (m_isPollSetDirty)
                    {
                        RebuildPollset();
                    }

                    var pollStart = Clock.NowMs();

                    // Set tickless to "infinity"
                    long tickless = pollStart + int.MaxValue;

                    // Find the When-value of the earliest timer..
                    foreach (var timer in m_timers)
                    {
                        // If it is enabled but no When is set yet,
                        if (timer.When == -1 && timer.Enable)
                        {
                            // Set this timer's When to now plus it's Interval.
                            timer.When = pollStart + timer.Interval;
                        }

                        // If it has a When and that is earlier than the earliest found thus far,
                        if (timer.When != -1 && tickless > timer.When)
                        {
                            // save that value.
                            tickless = timer.When;
                        }
                    }

                    // Compute a timeout value - how many milliseconds from now that the earliest-timer will expire.
                    var timeout = tickless - pollStart;

                    // Use zero to indicate it has already expired.
                    if (timeout < 0)
                    {
                        timeout = 0;
                    }

                    var isItemAvailable = false;

                    if (m_pollSet.Length != 0)
                    {
                        isItemAvailable = m_netMqSelector.Select(m_pollSet, m_pollSet.Length, timeout);
                    }
                    else if (timeout > 0)
                    {
                        //TODO: Do we really want to simply sleep and return, doing nothing during this interval?
                        //TODO: Should a large value be passed it will sleep for a month literally.
                        //      Solution should be different, but sleep is more natural here than in selector (timers are not selector concern).
                        Debug.Assert(timeout <= int.MaxValue);
                        Thread.Sleep((int)timeout);
                    }

                    // Get the expected end time in case we time out. This looks redundant but, unfortunately,
                    // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When'
                    // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens
                    // that 'Clock.NowMs() < pollStart + timeout'
                    var expectedPollEnd = !isItemAvailable ? pollStart + timeout : -1L;

                    // that way we make sure we can continue the loop if new timers are added.
                    // timers cannot be removed
                    foreach (var timer in m_timers)
                    {
                        if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1)
                        {
                            timer.InvokeElapsed(this);

                            if (timer.Enable)
                            {
                                timer.When = Clock.NowMs() + timer.Interval;
                            }
                        }
                    }

                    for (var i = 0; i < m_pollSet.Length; i++)
                    {
                        NetMQSelector.Item item = m_pollSet[i];

                        if (item.Socket != null)
                        {
                            NetMQSocket socket = m_pollact[i];

                            if (item.ResultEvent.HasError())
                            {
                                if (++socket.Errors > 1)
                                {
                                    Remove(socket);
                                    item.ResultEvent = PollEvents.None;
                                }
                            }
                            else
                            {
                                socket.Errors = 0;
                            }

                            if (item.ResultEvent != PollEvents.None)
                            {
                                socket.InvokeEvents(this, item.ResultEvent);
                            }
                        }
                        else if (item.ResultEvent.HasError() || item.ResultEvent.HasIn())
                        {
                            if (m_pollinSockets.TryGetValue(item.FileDescriptor, out Action <Socket> action))
                            {
                                action(item.FileDescriptor);
                            }
                        }
                    }
                }

#if !NET35
                // Try to dequeue and execute all pending tasks before stopping poller
                while (m_tasksQueue.TryDequeue(out Task task, TimeSpan.Zero))
                {
                    TryExecuteTask(task);
                }
#endif
            }
            finally
            {
                foreach (var socket in m_sockets.ToList())
                {
                    Remove(socket);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Poll as long as the given Func evaluates to true.
        /// </summary>
        /// <param name="condition">a Func that returns a boolean value, to evaluate on each poll-iteration to decide when to exit the loop</param>
        /// <exception cref="ObjectDisposedException">This poller must not have already been disposed.</exception>
        /// <exception cref="InvalidOperationException">This poller must not have already been started.</exception>
        private void PollWhile([NotNull, InstantHandle] Func <bool> condition)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("Poller is disposed");
            }

            if (m_isStarted)
            {
                throw new InvalidOperationException("Poller is started");
            }

            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "NetMQPollerThread";
            }

            m_isStoppedEvent.Reset();
            m_isStarted = true;
            try
            {
                // the sockets may have been created in another thread, to make sure we can fully use them we do full memory barrier
                // at the beginning of the loop
                Thread.MemoryBarrier();

                // Recalculate all timers now
                foreach (var timer in m_timers)
                {
                    if (timer.Enable)
                    {
                        timer.When = Clock.NowMs() + timer.Interval;
                    }
                }

                // Do this until the given Func evaluates to false...
                while (condition())
                {
                    if (m_isDirty)
                    {
                        RebuildPollset();
                    }

                    var pollStart = Clock.NowMs();
                    var timeout   = TicklessTimer();

                    var isItemsAvailable = false;

                    if (m_pollSize > 0)
                    {
                        isItemsAvailable = m_selector.Select(m_pollset, m_pollSize, timeout);
                    }
                    else
                    {
                        // Don't pass anything less than 0 to sleep or risk an out of range exception or worse - infinity. Do not sleep on 0 from orginal code.
                        if (timeout > 0)
                        {
                            //TODO: Do we really want to simply sleep and return, doing nothing during this interval?
                            //TODO: Should a large value be passed it will sleep for a month literaly.
                            //      Solution should be different, but sleep is more natural here than in selector (timers are not selector concern).
                            Thread.Sleep(timeout);
                        }
                    }

                    // Get the expected end time in case we time out. This looks redundant but, unfortunately,
                    // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When'
                    // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens
                    // that 'Clock.NowMs() < pollStart + timeout'
                    var expectedPollEnd = !isItemsAvailable ? pollStart + timeout : -1;

                    // that way we make sure we can continue the loop if new timers are added.
                    // timers cannot be removed
                    int timersCount = m_timers.Count;
                    for (int i = 0; i < timersCount; i++)
                    {
                        var timer = m_timers[i];

                        if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1)
                        {
                            timer.InvokeElapsed(this);

                            if (timer.Enable)
                            {
                                timer.When = timer.Interval + Clock.NowMs();
                            }
                        }
                    }

                    for (int itemNbr = 0; itemNbr < m_pollSize; itemNbr++)
                    {
                        SelectItem item = m_pollset[itemNbr];

                        if (item.Socket != null)
                        {
                            NetMQSocket socket = m_pollact[itemNbr];

                            if (item.ResultEvent.HasError())
                            {
                                socket.Errors++;

                                if (socket.Errors > 1)
                                {
                                    RemoveSocket(socket);
                                    item.ResultEvent = PollEvents.None;
                                }
                            }
                            else
                            {
                                socket.Errors = 0;
                            }

                            if (item.ResultEvent != PollEvents.None)
                            {
                                socket.InvokeEvents(this, item.ResultEvent);
                            }
                        }
                        else
                        {
                            if (item.ResultEvent.HasError() || item.ResultEvent.HasIn())
                            {
                                Action <Socket> action;

                                if (m_pollinSockets.TryGetValue(item.FileDescriptor, out action))
                                {
                                    action(item.FileDescriptor);
                                }
                            }
                        }
                    }

                    if (m_zombies.Count > 0)
                    {
                        // Now handle any timer zombies
                        // This is going to be slow if we have many zombies
                        foreach (var netMQTimer in m_zombies)
                        {
                            m_timers.Remove(netMQTimer);
                        }

                        m_zombies.Clear();
                    }
                }
            }
            finally
            {
                try
                {
                    foreach (var socket in m_sockets.ToList())
                    {
                        RemoveSocket(socket);
                    }
                }
                finally
                {
                    m_isStarted = false;
                    m_isStoppedEvent.Set();
                }
            }
        }
Ejemplo n.º 18
0
 public void Add(NetMQSocket socket)
 {
     m_poller.Add(socket);
     m_sockets.Add(socket);
 }
Ejemplo n.º 19
0
 public void Remove(NetMQSocket socket)
 {
     m_poller.Remove(socket);
     m_sockets.Remove(socket);
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="frontend">the socket that messages will be forwarded from</param>
        /// <param name="backend">the socket that messages will be forwarded to</param>
        /// <param name="controlIn">this socket will have incoming messages also sent to it - you can set this to null if not needed</param>
        /// <param name="controlOut">this socket will have outgoing messages also sent to it - you can set this to null if not needed</param>
        /// <param name="poller">an optional external poller to use within this proxy</param>
        public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket controlIn, [CanBeNull] NetMQSocket controlOut, [CanBeNull] INetMQPoller poller = null)
        {
            if (poller != null)
            {
                m_externalPoller = true;
                m_poller         = poller;
            }

            m_frontend   = frontend;
            m_backend    = backend;
            m_controlIn  = controlIn;
            m_controlOut = controlOut ?? controlIn;
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Create a new instance of a Proxy (NetMQ.Proxy)
 /// with the given sockets to serve as a front-end, a back-end, and a control socket.
 /// </summary>
 /// <param name="frontend">the socket that messages will be forwarded from</param>
 /// <param name="backend">the socket that messages will be forwarded to</param>
 /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
 /// <param name="poller">an optional external poller to use within this proxy</param>
 /// <exception cref="InvalidOperationException"><paramref name="poller"/> is not <c>null</c> and either <paramref name="frontend"/> or <paramref name="backend"/> are not contained within it.</exception>
 public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket control = null, [CanBeNull] INetMQPoller poller = null)
     : this(frontend, backend, control, null, poller)
 {
 }
Ejemplo n.º 22
0
 public SocketOptions([NotNull] NetMQSocket socket)
 {
     m_socket = socket;
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Create a new SocketOptions that references the given NetMQSocket.
 /// </summary>
 /// <param name="socket">the NetMQSocket for this SocketOptions to hold a reference to</param>
 public SocketOptions(NetMQSocket socket)
 {
     m_socket = socket;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Create a new NetMQSocketEventArgs referencing the given socket.
 /// </summary>
 /// <param name="socket">the NetMQSocket that this is about</param>
 public NetMQSocketEventArgs([NotNull] NetMQSocket socket)
 {
     Socket = socket;
 }
Ejemplo n.º 25
0
 public Proxy(NetMQSocket frontend, NetMQSocket backend, NetMQSocket control)
 {
     m_frontend = frontend;
     m_backend  = backend;
     m_control  = control;
 }
Ejemplo n.º 26
0
 internal static Context CreateContext(Model.IUser user, Header header, Model.Model dbContext, NetMQ.NetMQSocket socket)
 {
     return(new Context()
     {
         Header = header,
         User = user,
         Socket = socket,
         DbContext = dbContext
     });
 }
Ejemplo n.º 27
0
        private void PollWhile(Func <bool> condition)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("Poller is disposed");
            }

            if (m_isStarted)
            {
                throw new InvalidOperationException("Poller is started");
            }

            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "NetMQPollerThread";
            }

            m_isStoppedEvent.Reset();
            m_isStarted = true;
            try
            {
                // the sockets may have been created in another thread, to make sure we can fully use them we do full memory barried
                // at the begining of the loop
                Thread.MemoryBarrier();

                //  Recalculate all timers now
                foreach (NetMQTimer netMQTimer in m_timers)
                {
                    if (netMQTimer.Enable)
                    {
                        netMQTimer.When = Clock.NowMs() + netMQTimer.Interval;
                    }
                }

                while (condition())
                {
                    if (m_isDirty)
                    {
                        RebuildPollset();
                    }

                    var pollStart = Clock.NowMs();
                    var timeout   = TicklessTimer();

                    var nbEvents = ZMQ.Poll(m_pollset, m_pollSize, timeout);

                    // Get the expected end time in case we time out. This looks redundant but, unfortunately,
                    // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When'
                    // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens
                    // that 'Clock.NowMs() < pollStart + timeout'
                    var expectedPollEnd = nbEvents == 0 ? pollStart + timeout : -1;

                    // that way we make sure we can continue the loop if new timers are added.
                    // timers cannot be removed
                    int timersCount = m_timers.Count;
                    for (int i = 0; i < timersCount; i++)
                    {
                        var timer = m_timers[i];

                        if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1)
                        {
                            timer.InvokeElapsed(this);

                            if (timer.Enable)
                            {
                                timer.When = timer.Interval + Clock.NowMs();
                            }
                        }
                    }

                    for (int itemNbr = 0; itemNbr < m_pollSize; itemNbr++)
                    {
                        PollItem item = m_pollset[itemNbr];

                        if (item.Socket != null)
                        {
                            NetMQSocket socket = m_pollact[itemNbr] as NetMQSocket;

                            if (item.ResultEvent.HasFlag(PollEvents.PollError) && !socket.IgnoreErrors)
                            {
                                socket.Errors++;

                                if (socket.Errors > 1)
                                {
                                    RemoveSocket(socket);
                                    item.ResultEvent = PollEvents.None;
                                }
                            }
                            else
                            {
                                socket.Errors = 0;
                            }

                            if (item.ResultEvent != PollEvents.None)
                            {
                                socket.InvokeEvents(this, item.ResultEvent);
                            }
                        }
                        else
                        {
                            if (item.ResultEvent.HasFlag(PollEvents.PollError) || item.ResultEvent.HasFlag(PollEvents.PollIn))
                            {
                                Action <Socket> action;

                                if (m_pollinSockets.TryGetValue(item.FileDescriptor, out action))
                                {
                                    action(item.FileDescriptor);
                                }
                            }
                        }
                    }

                    if (m_zombies.Any())
                    {
                        //  Now handle any timer zombies
                        //  This is going to be slow if we have many zombies
                        foreach (NetMQTimer netMQTimer in m_zombies)
                        {
                            m_timers.Remove(netMQTimer);
                        }

                        m_zombies.Clear();
                    }
                }
            }
            finally
            {
                m_isStoppedEvent.Set();

                foreach (var socket in m_sockets.ToList())
                {
                    RemoveSocket(socket);
                }
            }
        }
 /// <summary>
 /// Create a new ErrorPollingException containing the given message and a reference to the given socket.
 /// </summary>
 /// <param name="message">the textual description of what gave rise to this exception, to be exposed as the Message property</param>
 /// <param name="socket">a reference to the socket, to be exposed via the Socket property</param>
 public ErrorPollingException(string message, NetMQSocket socket)
     : base(message)
 {
     Socket = socket;
 }
Ejemplo n.º 29
0
 public PollerPollItem(NetMQSocket socket, PollEvents events)
     : base(socket.SocketHandle, events)
 {
     m_socket = socket;
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets whether <paramref name="socket"/> has been added to this <see cref="Poller"/>.
 /// </summary>
 public bool ContainsSocket(NetMQSocket socket)
 {
     return(m_sockets.Contains(socket));
 }