InitEmpty() public method

Clear this Msg to empty - ie, set MsgFlags to None, MsgType to Empty, and clear the Data.
public InitEmpty ( ) : void
return void
コード例 #1
0
ファイル: Program.cs プロジェクト: bbqchickenrobot/netmq
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: local_thr <bind-to> <message-size> <message-count>");
                return 1;
            }

            string bindTo = args[0];
            int messageSize = int.Parse(args[1]);
            int messageCount = int.Parse(args[2]);

            using (var context = NetMQContext.Create())
            using (var pullSocket = context.CreatePullSocket())
            {
                pullSocket.Bind(bindTo);

                var message = new Msg();
                message.InitEmpty();

                pullSocket.Receive(ref message, SendReceiveOptions.None);

                var stopWatch = Stopwatch.StartNew();
                for (int i = 0; i != messageCount - 1; i++)
                {
                    pullSocket.Receive(ref message, SendReceiveOptions.None);
                    if (message.Size != messageSize)
                    {
                        Console.WriteLine("message of incorrect size received. Received: " + message.Size + " Expected: " + messageSize);
                        return -1;
                    }
                }
                stopWatch.Stop();
                var millisecondsElapsed = stopWatch.ElapsedMilliseconds;
                if (millisecondsElapsed == 0)
                    millisecondsElapsed = 1;

                message.Close();

                double messagesPerSecond = (double)messageCount/millisecondsElapsed*1000;
                double megabits = messagesPerSecond*messageSize*8/1000000;

                Console.WriteLine("message size: {0} [B]", messageSize);
                Console.WriteLine("message count: {0}", messageCount);
                Console.WriteLine("mean throughput: {0:0.000} [msg/s]", messagesPerSecond);
                Console.WriteLine("mean throughput: {0:0.000} [Mb/s]", megabits);

                pullSocket.Close();
            }

            return 0;
        }
コード例 #2
0
ファイル: Msg.cs プロジェクト: fhchina/netmq
        public void Move([NotNull] ref Msg src)
        {
            //  Check the validity of the source.
            if (!src.Check())
            {
                throw new FaultException();
            }

            Close();

            this = src;

            src.InitEmpty();
        }
コード例 #3
0
        public static byte[] ReceiveFrameBytes([NotNull] this IReceivingSocket socket, out bool more)
        {
            var msg = new Msg();
            msg.InitEmpty();

            socket.Receive(ref msg);

            var data = msg.CloneData();

            more = msg.HasMore;

            msg.Close();
            return data;
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        public static byte[] ReceiveFrameBytes([NotNull] this IReceivingSocket socket, out bool more)
        {
            var msg = new Msg();

            msg.InitEmpty();

            socket.Receive(ref msg);

            var data = msg.CloneData();

            more = msg.HasMore;

            msg.Close();
            return(data);
        }
コード例 #6
0
        public static byte[] Receive([NotNull] this IReceivingSocket socket, SendReceiveOptions options, out bool hasMore)
        {
            var msg = new Msg();
            msg.InitEmpty();

            socket.Receive(ref msg, options);

            var data = msg.CloneData();

            hasMore = msg.HasMore;

            msg.Close();

            return data;
        }
コード例 #7
0
        public static List <string> ReceiveMultipartStrings([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, int expectedFrameCount = 4)
        {
            var frames = new List <string>(expectedFrameCount);

            var msg = new Msg();

            msg.InitEmpty();

            do
            {
                socket.Receive(ref msg);
                frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));
            }while (msg.HasMore);

            msg.Close();
            return(frames);
        }
コード例 #8
0
        public static NetMQMessage ReceiveMultipartMessage([NotNull] this IReceivingSocket socket, int expectedFrameCount = 4)
        {
            var msg = new Msg();

            msg.InitEmpty();

            var message = new NetMQMessage(expectedFrameCount);

            do
            {
                socket.Receive(ref msg);
                message.Append(msg.CloneData());
            }while (msg.HasMore);

            msg.Close();
            return(message);
        }
コード例 #9
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref name="socket"/>, then ignore its content.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// Indicate whether further frames exist via <paramref name="more"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
        public static bool TrySkipFrame([NotNull] this IReceivingSocket socket, TimeSpan timeout, out bool more)
        {
            var msg = new Msg();

            msg.InitEmpty();

            if (!socket.TryReceive(ref msg, timeout))
            {
                more = false;
                msg.Close();
                return(false);
            }

            more = msg.HasMore;
            msg.Close();
            return(true);
        }
コード例 #10
0
        /// <summary>
        /// Close this Msg and make it reference the given source Msg, and then clear the Msg to empty.
        /// </summary>
        /// <param name="src">the source-Msg to become</param>
        /// <exception cref="FaultException">The object is not initialised.</exception>
        public void Move(ref Msg src)
        {
            // Check the validity of the source.
            if (!src.IsInitialised)
            {
                throw new FaultException("Cannot move an uninitialised Msg.");
            }

            if (IsInitialised)
            {
                Close();
            }

            this = src;

            src.InitEmpty();
        }
コード例 #11
0
ファイル: AsyncReceiveExtensions.cs プロジェクト: zredb/netmq
        /// <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);
        }
コード例 #12
0
        public static string ReceiveFrameString([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, out bool more)
        {
            var msg = new Msg();

            msg.InitEmpty();

            socket.Receive(ref msg);

            more = msg.HasMore;

            var str = msg.Size > 0
                ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                : string.Empty;

            msg.Close();
            return(str);
        }
コード例 #13
0
        /// <summary>
        /// Receive a bytes from <paramref name="socket"/>, blocking until one arrives.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>The content of the received message.</returns>
        /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
        public static byte[] ReceiveBytes(this IThreadSafeInSocket socket,
                                          CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                var data = msg.CloneData();
                return(data);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #14
0
        public static (uint, byte[]) ReceiveBytes(this IRoutingIdSocket socket, CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                var data      = msg.CloneData();
                var routingId = msg.RoutingId;
                return(routingId, data);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #15
0
ファイル: NetMQQueue.cs プロジェクト: r618/netmq
        /// <summary>
        /// Create new NetMQQueue.
        /// </summary>
        /// <param name="capacity">The capacity of the queue, use zero for unlimited</param>
        public NetMQQueue(int capacity = 0)
        {
            if (capacity < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(capacity));
            }

            m_queue = new ConcurrentQueue <T>();
            PairSocket.CreateSocketPair(out m_writer, out m_reader);

            m_writer.Options.SendHighWatermark = m_reader.Options.ReceiveHighWatermark = capacity / 2;

            m_eventDelegator = new EventDelegator <NetMQQueueEventArgs <T> >(
                () => m_reader.ReceiveReady += OnReceiveReady,
                () => m_reader.ReceiveReady -= OnReceiveReady);

            m_dequeueMsg = new Msg();
            m_dequeueMsg.InitEmpty();
        }
コード例 #16
0
        /// <summary>
        /// Attempt to receive a byte-array <paramref name="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="bytes">The content of the received message, or <c>null</c> if no message was available.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        /// <remarks>The method would return false if cancellation has had requested.</remarks>
        public static bool TryReceiveBytes(this IThreadSafeInSocket socket, TimeSpan timeout,
                                           [NotNullWhen(returnValue: true)] out byte[]?bytes, CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            if (!socket.TryReceive(ref msg, timeout, cancellationToken))
            {
                msg.Close();
                bytes = null;
                return(false);
            }

            bytes = msg.CloneData();

            msg.Close();
            return(true);
        }
コード例 #17
0
        /// <summary>
        /// Receive a string from <paramref name="socket"/>, blocking until one arrives, and decode using <paramref name="encoding"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="encoding">The encoding used to convert the data to a string.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>The content of the received message.</returns>
        /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
        public static string ReceiveString(this IThreadSafeInSocket socket, Encoding encoding,
                                           CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                return(msg.Size > 0
                    ? msg.GetString(encoding)
                    : string.Empty);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #18
0
        /// <summary>
        /// Receive a bytes from <paramref name="socket"/>, blocking until one arrives.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>Tuple of group and received bytes</returns>
        /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
        public static (string, byte[]) ReceiveBytes(this IGroupInSocket socket,
                                                    CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                var data  = msg.CloneData();
                var group = msg.Group;
                return(group, data);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #19
0
        public static (uint, string) ReceiveString(this IRoutingIdSocket socket, Encoding encoding, CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                var routingId = msg.RoutingId;
                var str       = msg.Size > 0
                    ? msg.GetString(encoding)
                    : string.Empty;
                return(routingId, str);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #20
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref name="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// Indicate whether further frames exist via <paramref name="more"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="bytes">The content of the received message frame, or <c>null</c> if no message was available.</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveFrameBytes([NotNull] this IReceivingSocket socket, TimeSpan timeout, out byte[] bytes, out bool more)
        {
            var msg = new Msg();

            msg.InitEmpty();

            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                bytes = null;
                more  = false;
                return(false);
            }

            bytes = msg.CloneData();
            more  = msg.HasMore;

            msg.Close();
            return(true);
        }
コード例 #21
0
        public static string ReceiveString(this IReceivingSocket socket, Encoding encoding, SendReceiveOptions options, out bool hasMore)
        {
            Msg msg = new Msg();

            msg.InitEmpty();

            socket.Receive(ref msg, options);

            hasMore = msg.HasMore;

            string data = string.Empty;

            if (msg.Size > 0)
            {
                data = encoding.GetString(msg.Data, 0, msg.Size);
            }

            msg.Close();

            return(data);
        }
コード例 #22
0
        /// <summary>
        /// Receive a string from <paramref name="socket"/>, blocking until one arrives, and decode using <paramref name="encoding"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="encoding">The encoding used to convert the data to a string.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>Tuple of group and the content of the received message as a string.</returns>
        /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
        public static (string, string) ReceiveString(this IGroupInSocket socket, Encoding encoding,
                                                     CancellationToken cancellationToken = default)
        {
            var msg = new Msg();

            msg.InitEmpty();

            try
            {
                socket.Receive(ref msg, cancellationToken);
                var group = msg.Group;
                var str   = msg.Size > 0
                    ? msg.GetString(encoding)
                    : string.Empty;
                return(group, str);
            }
            finally
            {
                msg.Close();
            }
        }
コード例 #23
0
        public static byte[] Receive([NotNull] this IReceivingSocket socket, SendReceiveOptions options, out bool hasMore)
        {
            var msg = new Msg();

            msg.InitEmpty();

            socket.Receive(ref msg, options);

            var data = new byte[msg.Size];

            if (msg.Size > 0)
            {
                Buffer.BlockCopy(msg.Data, 0, data, 0, msg.Size);
            }

            hasMore = msg.HasMore;

            msg.Close();

            return(data);
        }
コード例 #24
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref name="socket"/>, then ignore their contents.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
        public static bool TrySkipMultipartMessage([NotNull] this IReceivingSocket socket, TimeSpan timeout)
        {
            var msg = new Msg();

            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return(false);
            }

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
            }

            msg.Close();
            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Attempt to receive a valid signal from <paramref name="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="signal"><c>true</c> if the received signal was zero, otherwise <c>false</c>. If no signal received, <c>false</c>.</param>
        /// <returns><c>true</c> if a valid signal was observed, otherwise <c>false</c>.</returns>
        public static bool TryReceiveSignal([NotNull] this IReceivingSocket socket, TimeSpan timeout, out bool signal)
        {
            var msg = new Msg();

            msg.InitEmpty();

            // TODO use clock to enforce timeout across multiple loop iterations — if invalid messages are received regularly, the method may not return once the timeout elapses

            while (true)
            {
                if (!socket.TryReceive(ref msg, timeout))
                {
                    signal = false;
                    msg.Close();
                    return(false);
                }

                var isMultiFrame = msg.HasMore;
                while (msg.HasMore)
                {
                    socket.Receive(ref msg);
                }

                if (isMultiFrame || msg.Size != 8)
                {
                    continue;
                }

                var signalValue = NetworkOrderBitsConverter.ToInt64(msg.Data);

                if ((signalValue & 0x7FFFFFFFFFFFFF00L) == 0x7766554433221100L)
                {
                    signal = (signalValue & 255) == 0;
                    msg.Close();
                    return(true);
                }
            }
        }
コード例 #26
0
        /// <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);
        }
コード例 #27
0
        public static string ReceiveString([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, SendReceiveOptions options, out bool hasMore)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            var msg = new Msg();

            msg.InitEmpty();

            socket.Receive(ref msg, options);

            hasMore = msg.HasMore;

            string data = msg.Size > 0
                ? encoding.GetString(msg.Data, 0, msg.Size)
                : string.Empty;

            msg.Close();

            return(data);
        }
コード例 #28
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref name="socket"/>, and decode as a string using <paramref name="encoding"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="encoding">The encoding used to convert the frame's data to a string.</param>
        /// <param name="frameString">The content of the received message frame as a string, or <c>null</c> if no message was available.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveFrameString([NotNull] this IReceivingSocket socket, TimeSpan timeout, [NotNull] Encoding encoding, out string frameString, out bool more)
        {
            var msg = new Msg();

            msg.InitEmpty();

            if (socket.TryReceive(ref msg, timeout))
            {
                more = msg.HasMore;

                frameString = msg.Size > 0
                    ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                    : string.Empty;

                msg.Close();
                return(true);
            }

            frameString = null;
            more        = false;
            msg.Close();
            return(false);
        }
コード例 #29
0
        /// <summary>
        /// Receive all frames of the next message from <paramref name="socket"/>, blocking until a message arrives.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="frames">Reference to a list for return values. If <c>null</c> a new instance will be assigned, otherwise the provided list will be cleared and populated.</param>
        /// <param name="expectedFrameCount">Optional initial <see cref="List{T}.Capacity"/> for the returned <see cref="List{T}"/>.</param>
        public static void ReceiveMultipartBytes([NotNull] this IReceivingSocket socket, ref List <byte[]> frames, int expectedFrameCount = 4)
        {
            if (frames == null)
            {
                frames = new List <byte[]>(expectedFrameCount);
            }
            else
            {
                frames.Clear();
            }

            var msg = new Msg();

            msg.InitEmpty();

            do
            {
                socket.Receive(ref msg);
                frames.Add(msg.CloneData());
            }while (msg.HasMore);

            msg.Close();
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: wangkai2014/netmq
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: local_lat <bind-to> <message-size> <roundtrip-count>");
                return 1;
            }

            string bindTo = args[0];
            int messageSize = int.Parse(args[1]);
            int roundtripCount = int.Parse(args[2]);

            using (var context = NetMQContext.Create())
            using (var rep = context.CreateResponseSocket())
            {
                rep.Bind(bindTo);

                var msg = new Msg();
                msg.InitEmpty();

                for (int i = 0; i != roundtripCount; i++)
                {
                    rep.Receive(ref msg);
                    if (msg.Size != messageSize)
                    {
                        Console.WriteLine("message of incorrect size received. Received: " + msg.Size + " Expected: " + messageSize);
                        return -1;
                    }

                    rep.Send(ref msg, SendReceiveOptions.None);
                }

                msg.Close();
            }

            return 0;
        }
コード例 #31
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref name="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="message">The received message. Untouched if no message was available.</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>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveMultipartMessage([NotNull] this IReceivingSocket socket, TimeSpan timeout, [CanBeNull] ref NetMQMessage message, int expectedFrameCount = 4)
        {
            var msg = new Msg();

            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return(false);
            }

            // We have one, so prepare the container
            if (message == null)
            {
                message = new NetMQMessage(expectedFrameCount);
            }
            else
            {
                message.Clear();
            }

            // Add the frame
            message.Append(new NetMQFrame(msg.CloneData()));

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                message.Append(new NetMQFrame(msg.CloneData()));
            }

            msg.Close();
            return(true);
        }
コード例 #32
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref name="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="frames">Reference to a list for return values. If <c>null</c> a new instance will be assigned, otherwise the provided list will be cleared and populated.</param>
        /// <param name="expectedFrameCount">Optional initial <see cref="List{T}.Capacity"/> for the returned <see cref="List{T}"/>.</param>
        public static bool TryReceiveMultipartBytes([NotNull] this IReceivingSocket socket, TimeSpan timeout, ref List <byte[]> frames, int expectedFrameCount = 4)
        {
            var msg = new Msg();

            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return(false);
            }

            // We have one, so prepare the container
            if (frames == null)
            {
                frames = new List <byte[]>(expectedFrameCount);
            }
            else
            {
                frames.Clear();
            }

            // Add the frame
            frames.Add(msg.CloneData());

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                frames.Add(msg.CloneData());
            }

            msg.Close();
            return(true);
        }
コード例 #33
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref name="socket"/>, and decode them as strings using <paramref name="encoding"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="encoding">The encoding used to convert the frame's data to a string.</param>
        /// <param name="frames">The frames of the received message as strings. Untouched if no message was available.</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>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveMultipartStrings([NotNull] this IReceivingSocket socket, TimeSpan timeout, [NotNull] Encoding encoding, [CanBeNull] ref List <string> frames, int expectedFrameCount = 4)
        {
            var msg = new Msg();

            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return(false);
            }

            // We have one, so prepare the container
            if (frames == null)
            {
                frames = new List <string>(expectedFrameCount);
            }
            else
            {
                frames.Clear();
            }

            // Add the frame
            frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));
            }

            msg.Close();
            return(true);
        }
コード例 #34
0
 /// <summary>
 /// Attempt to receive a single frame from <paramref cref="socket"/>, then ignore its content.
 /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
 /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
 public static bool TrySkipFrame([NotNull] this IReceivingSocket socket, TimeSpan timeout)
 {
     var msg = new Msg();
     msg.InitEmpty();
     var received = socket.TryReceive(ref msg, timeout);
     msg.Close();
     return received;
 }
コード例 #35
0
 /// <summary>
 /// Attempt to receive a single frame from <paramref cref="socket"/>, then ignore its content.
 /// If no message is immediately available, return <c>false</c>.
 /// Indicate whether further frames exist via <paramref name="more"/>.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
 /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
 public static bool TrySkipFrame([NotNull] this IReceivingSocket socket, out bool more)
 {
     var msg = new Msg();
     msg.InitEmpty();
     var result = socket.TryReceive(ref msg, TimeSpan.Zero);
     more = msg.HasMore;
     msg.Close();
     return result;
 }
コード例 #36
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref cref="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// Indicate whether further frames exist via <paramref name="more"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="bytes">The content of the received message frame, or <c>null</c> if no message was available.</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveFrameBytes([NotNull] this IReceivingSocket socket, TimeSpan timeout, out byte[] bytes, out bool more)
        {
            var msg = new Msg();
            msg.InitEmpty();

            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                bytes = null;
                more = false;
                return false;
            }

            bytes = msg.CloneData();
            more = msg.HasMore;

            msg.Close();
            return true;
        }
コード例 #37
0
 /// <summary>
 /// Receive a single frame from <paramref cref="socket"/>, blocking until one arrives, then ignore its content.
 /// Indicate whether further frames exist via <paramref name="more"/>.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
 public static void SkipFrame([NotNull] this IReceivingSocket socket, out bool more)
 {
     var msg = new Msg();
     msg.InitEmpty();
     socket.Receive(ref msg);
     more = msg.HasMore;
     msg.Close();
 }
コード例 #38
0
ファイル: Proxy.cs プロジェクト: bbqchickenrobot/netmq
        private static void ProxyBetween(NetMQSocket from, NetMQSocket to, [CanBeNull] NetMQSocket control)
        {
            var msg = new Msg();
            msg.InitEmpty();

            var copy = new Msg();
            copy.InitEmpty();

            while (true)
            {
                from.Receive(ref msg, SendReceiveOptions.None);
                bool more = from.Options.ReceiveMore;

                if (control != null)
                {
                    copy.Copy(ref msg);

                    control.Send(ref copy, more ? SendReceiveOptions.SendMore : SendReceiveOptions.None);
                }

                to.Send(ref msg, more ? SendReceiveOptions.SendMore : SendReceiveOptions.None);

                if (!more)
                {
                    break;
                }
            }

            copy.Close();
            msg.Close();
        }
コード例 #39
0
        /// <summary>
        /// Receive all frames of the next message from <paramref cref="socket"/>, blocking until a message arrives.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="frames">Reference to a list for return values. If <c>null</c> a new instance will be assigned, otherwise the provided list will be cleared and populated.</param>
        /// <param name="expectedFrameCount">Optional initial <see cref="List{T}.Capacity"/> for the returned <see cref="List{T}"/>.</param>
        public static void ReceiveMultipartBytes([NotNull] this IReceivingSocket socket, ref List<byte[]> frames, int expectedFrameCount = 4)
        {
            if (frames == null)
                frames = new List<byte[]>(expectedFrameCount);
            else
                frames.Clear();

            var msg = new Msg();
            msg.InitEmpty();

            do
            {
                socket.Receive(ref msg);
                frames.Add(msg.CloneData());
            }
            while (msg.HasMore);

            msg.Close();
        }
コード例 #40
0
 /// <summary>
 /// Attempt to receive all frames of the next message from <paramref cref="socket"/>, then ignore their contents.
 /// If no message is immediately available, return <c>false</c>.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
 public static bool TrySkipMultipartMessage([NotNull] this IReceivingSocket socket)
 {
     var msg = new Msg();
     msg.InitEmpty();
     var received = socket.TryReceive(ref msg, TimeSpan.Zero);
     msg.Close();
     return received;
 }
コード例 #41
0
        public static void ReceiveMessage([NotNull] this IReceivingSocket socket, [NotNull] NetMQMessage message, bool dontWait = false)
        {
            message.Clear();

            var msg = new Msg();
            msg.InitEmpty();

            do
            {
                socket.Receive(ref msg, dontWait ? SendReceiveOptions.DontWait : SendReceiveOptions.None);
                message.Append(msg.CloneData());
            }
            while (msg.HasMore);

            msg.Close();
        }
コード例 #42
0
        public static string ReceiveFrameString([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, out bool more)
        {
            var msg = new Msg();
            msg.InitEmpty();

            socket.Receive(ref msg);

            more = msg.HasMore;

            var str = msg.Size > 0
                ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                : string.Empty;

            msg.Close();
            return str;
        }
コード例 #43
0
        public static string ReceiveString([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, SendReceiveOptions options, out bool hasMore)
        {
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            var msg = new Msg();
            msg.InitEmpty();

            socket.Receive(ref msg, options);

            hasMore = msg.HasMore;

            string data = msg.Size > 0
                ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                : string.Empty;

            msg.Close();
            return data;
        }
コード例 #44
0
ファイル: Msg.cs プロジェクト: bbqchickenrobot/netmq
        /// <summary>
        /// Close this Msg and make it reference the given source Msg, and then clear the Msg to empty.
        /// </summary>
        /// <param name="src">the source-Msg to become</param>
        public void Move(ref Msg src)
        {
            // Check the validity of the source.
            if (!src.IsInitialised)
                throw new FaultException("Cannot move an uninitialised Msg.");

            if (IsInitialised)
                Close();

            this = src;

            src.InitEmpty();
        }
コード例 #45
0
ファイル: Proxy.cs プロジェクト: somdoron/netmq
        private static void ProxyBetween(IReceivingSocket from, IOutgoingSocket to, [CanBeNull] IOutgoingSocket control)
        {
            var msg = new Msg();
            msg.InitEmpty();

            var copy = new Msg();
            copy.InitEmpty();

            while (true)
            {
                from.Receive(ref msg);
                var more = msg.HasMore;

                if (control != null)
                {
                    copy.Copy(ref msg);

                    control.Send(ref copy, more);
                }

                to.Send(ref msg, more);

                if (!more)
                    break;
            }

            copy.Close();
            msg.Close();
        }
コード例 #46
0
        public static List<string> ReceiveMultipartStrings([NotNull] this IReceivingSocket socket, [NotNull] Encoding encoding, int expectedFrameCount = 4)
        {
            var frames = new List<string>(expectedFrameCount);

            var msg = new Msg();
            msg.InitEmpty();

            do
            {
                socket.Receive(ref msg);
                frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));
            }
            while (msg.HasMore);

            msg.Close();
            return frames;
        }
コード例 #47
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref cref="socket"/>, then ignore its content.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// Indicate whether further frames exist via <paramref name="more"/>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
        public static bool TrySkipFrame([NotNull] this IReceivingSocket socket, TimeSpan timeout, out bool more)
        {
            var msg = new Msg();
            msg.InitEmpty();

            if (!socket.TryReceive(ref msg, timeout))
            {
                more = false;
                msg.Close();
                return false;
            }

            more = msg.HasMore;
            msg.Close();
            return true;
        }
コード例 #48
0
        /// <summary>
        /// Receive frames from <paramref cref="socket"/>, blocking until a valid signal arrives.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <returns><c>true</c> if the received signal was zero, otherwise <c>false</c>.</returns>
        public static bool ReceiveSignal([NotNull] this IReceivingSocket socket)
        {
            var msg = new Msg();
            msg.InitEmpty();

            while (true)
            {
                socket.Receive(ref msg);

                var isMultiFrame = msg.HasMore;
                while (msg.HasMore)
                {
                    socket.Receive(ref msg);
                }

                if (isMultiFrame || msg.Size != 8)
                    continue;

                var signalValue = NetworkOrderBitsConverter.ToInt64(msg.Data);

                if ((signalValue & 0x7FFFFFFFFFFFFF00L) == 0x7766554433221100L)
                {
                    msg.Close();
                    return (signalValue & 255) == 0;
                }
            }
        }
コード例 #49
0
 /// <summary>
 /// Receive all frames of the next message from <paramref cref="socket"/>, blocking until a message arrives, then ignore their contents.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 public static void SkipMultipartMessage([NotNull] this IReceivingSocket socket)
 {
     var msg = new Msg();
     msg.InitEmpty();
     do
     {
         socket.Receive(ref msg);
     }
     while (msg.HasMore);
     msg.Close();
 }
コード例 #50
0
        /// <summary>
        /// Attempt to receive a valid signal from <paramref cref="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="signal"><c>true</c> if the received signal was zero, otherwise <c>false</c>. If no signal received, <c>false</c>.</param>
        /// <returns><c>true</c> if a valid signal was observed, otherwise <c>false</c>.</returns>
        public static bool TryReceiveSignal([NotNull] this IReceivingSocket socket, TimeSpan timeout, out bool signal)
        {
            var msg = new Msg();
            msg.InitEmpty();

            // TODO use clock to enforce timeout across multiple loop iterations — if invalid messages are received regularly, the method may not return once the timeout elapses

            while (true)
            {
                if (!socket.TryReceive(ref msg, timeout))
                {
                    signal = false;
                    msg.Close();
                    return false;
                }

                var isMultiFrame = msg.HasMore;
                while (msg.HasMore)
                {
                    socket.Receive(ref msg);
                }

                if (isMultiFrame || msg.Size != 8)
                    continue;

                var signalValue = NetworkOrderBitsConverter.ToInt64(msg.Data);

                if ((signalValue & 0x7FFFFFFFFFFFFF00L) == 0x7766554433221100L)
                {
                    signal = (signalValue & 255) == 0;
                    msg.Close();
                    return true;
                }
            }
        }
コード例 #51
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref cref="socket"/>, then ignore their contents.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
        public static bool TrySkipMultipartMessage([NotNull] this IReceivingSocket socket, TimeSpan timeout)
        {
            var msg = new Msg();
            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return false;
            }

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
            }

            msg.Close();
            return true;
        }
コード例 #52
0
 /// <summary>
 /// Receive a single frame from <paramref cref="socket"/>, blocking until one arrives, then ignore its content.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 public static void SkipFrame([NotNull] this IReceivingSocket socket)
 {
     var msg = new Msg();
     msg.InitEmpty();
     socket.Receive(ref msg);
     msg.Close();
 }
コード例 #53
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref cref="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="frames">Reference to a list for return values. If <c>null</c> a new instance will be assigned, otherwise the provided list will be cleared and populated.</param>
        /// <param name="expectedFrameCount">Optional initial <see cref="List{T}.Capacity"/> for the returned <see cref="List{T}"/>.</param>
        public static bool TryReceiveMultipartBytes([NotNull] this IReceivingSocket socket, TimeSpan timeout, ref List<byte[]> frames, int expectedFrameCount = 4)
        {
            var msg = new Msg();
            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return false;
            }

            // We have one, so prepare the container
            if (frames == null)
                frames = new List<byte[]>(expectedFrameCount);
            else
                frames.Clear();

            // Add the frame
            frames.Add(msg.CloneData());

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                frames.Add(msg.CloneData());
            }

            msg.Close();
            return true;
        }
コード例 #54
0
        public void MessagePoll()
        {
            NetMQ.Msg msg = new NetMQ.Msg();
            msg.InitEmpty();
            if (_socket.TryReceive(ref msg, TimeSpan.FromMilliseconds(1)))
            {
                switch ((MessageType)msg.Data[0])
                {
                case MessageType.Heartbeat:     //heartbeat

                    break;

                case MessageType.Debug:     // debug
                    if (_socket.TryReceive(ref msg, TimeSpan.FromMilliseconds(1)))
                    {
                        string text = System.Text.Encoding.ASCII.GetString(msg.Data);
                        if (text == "{}")
                        {
                            break;
                        }
                        JObject jo   = (JObject)JsonConvert.DeserializeObject(text);
                        var     type = jo["type"].Value <string>();
                        if (type == "get-program")
                        {
                            GameState.Program = DreyProgram.FromJson(jo);
                            DataArrived?.Invoke(new GetProgramEventArgs()
                            {
                                Program = GameState.Program
                            });
                        }
                        else if (type == "announce")
                        {
                            var deserialized = JsonConvert.DeserializeObject <GameState>(text, new ObjectTypeDeserializer());
                            GameState.Announce(deserialized);
                            DataArrived?.Invoke(new AnnounceEventArgs()
                            {
                                State = GameState
                            });
                        }
                        else if (type == "set-breakpoint")
                        {
                            var address = jo["address"].Value <int>();
                            GameState.Breakpoints.Add(address);
                            DataArrived?.Invoke(new BreakPointEventArgs()
                            {
                                Address = address, Set = true
                            });
                        }
                        else if (type == "clear-breakpoint")
                        {
                            var address = jo["address"].Value <int>();
                            GameState.Breakpoints.Remove(address);
                            DataArrived?.Invoke(new BreakPointEventArgs()
                            {
                                Address = address, Set = false
                            });
                        }
                        else if (type == "debug-msg")
                        {
                            var msg2 = jo["message"].Value <string>();
                            DataArrived?.Invoke(new DebugMessageEventArgs()
                            {
                                Message = msg2
                            });
                        }
                        else if (type == "debug-msg-line")
                        {
                            var msg3 = jo["message"].Value <string>();
                            DataArrived?.Invoke(new DebugMessageEventArgs()
                            {
                                Message = msg3 + Environment.NewLine
                            });
                        }
                    }
                    break;

                case MessageType.Data:     // data
                    if (_socket.TryReceive(ref msg, TimeSpan.FromMilliseconds(1)))
                    {
                        string text = System.Text.Encoding.ASCII.GetString(msg.Data);

                        var ser = new Newtonsoft.Json.JsonSerializer();
                        using (var reader = new JsonTextReader(new StringReader(text)))
                        {
                            PendingChoice choice = ser.Deserialize <PendingChoice>(reader);
                            GameState.PendingChoice = choice;
                        }

                        DataArrived?.Invoke(new DataEventArgs()
                        {
                            Data = text
                        });
                    }

                    break;
                }
            }
        }
コード例 #55
0
        /// <summary>
        /// Attempt to receive a single frame from <paramref cref="socket"/>, and decode as a string using <paramref name="encoding"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="encoding">The encoding used to convert the frame's data to a string.</param>
        /// <param name="frameString">The content of the received message frame as a string, or <c>null</c> if no message was available.</param>
        /// <param name="more"><c>true</c> if another frame of the same message follows, otherwise <c>false</c>.</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveFrameString([NotNull] this IReceivingSocket socket, TimeSpan timeout, [NotNull] Encoding encoding, out string frameString, out bool more)
        {
            var msg = new Msg();
            msg.InitEmpty();

            if (socket.TryReceive(ref msg, timeout))
            {
                more = msg.HasMore;

                frameString = msg.Size > 0
                    ? encoding.GetString(msg.Data, msg.Offset, msg.Size)
                    : string.Empty;

                msg.Close();
                return true;
            }

            frameString = null;
            more = false;
            msg.Close();
            return false;
        }
コード例 #56
0
        public static NetMQMessage ReceiveMultipartMessage([NotNull] this IReceivingSocket socket, int expectedFrameCount = 4)
        {
            var msg = new Msg();
            msg.InitEmpty();

            var message = new NetMQMessage(expectedFrameCount);

            do
            {
                socket.Receive(ref msg);
                message.Append(msg.CloneData());
            }
            while (msg.HasMore);

            msg.Close();
            return message;
        }
コード例 #57
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref cref="socket"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="message">The received message. Untouched if no message was available.</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>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveMultipartMessage([NotNull] this IReceivingSocket socket, TimeSpan timeout, [CanBeNull] ref NetMQMessage message, int expectedFrameCount = 4)
        {
            var msg = new Msg();
            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return false;
            }

            // We have one, so prepare the container
            if (message == null)
                message = new NetMQMessage(expectedFrameCount);
            else
                message.Clear();

            // Add the frame
            message.Append(new NetMQFrame(msg.CloneData()));

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                message.Append(new NetMQFrame(msg.CloneData()));
            }

            msg.Close();
            return true;
        }
コード例 #58
0
ファイル: MmiHelper.cs プロジェクト: MischaJ/mmi-csharp
        public static MmiMessage ReceiveMessageAndData(NetMQSocket socket)
        {
            MmiMessage message;

            lock (socket)
            {
                string json;
                bool more;
                var msg = new Msg();
                msg.InitEmpty();
                if (!socket.TryReceiveFrameString(Timeout, out json, out more))
                {
                    throw new NetMQException("Timeout during receive");
                }

                message = new MmiMessage { JsonString = json };
                message.FillFromJson(json);

                // receive data
                if (socket.HasIn)
                {
                    byte[] bytes;
                    if (!socket.TryReceiveFrameBytes(Timeout, out bytes))
                    {
                        throw new NetMQException("Timeout during receive bytes");
                    }

                    message.Values = BytesToArray(bytes, message.DataType, message.Shape);
                }
            }

            return message;
        }
コード例 #59
0
        /// <summary>
        /// Attempt to receive all frames of the next message from <paramref cref="socket"/>, and decode them as strings using <paramref name="encoding"/>.
        /// If no message is available within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">The socket to receive from.</param>
        /// <param name="timeout">The maximum period of time to wait for a message to become available.</param>
        /// <param name="encoding">The encoding used to convert the frame's data to a string.</param>
        /// <param name="frames">The frames of the received message as strings. Untouched if no message was available.</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>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TryReceiveMultipartStrings([NotNull] this IReceivingSocket socket, TimeSpan timeout, [NotNull] Encoding encoding, [CanBeNull] ref List<string> frames, int expectedFrameCount = 4)
        {
            var msg = new Msg();
            msg.InitEmpty();

            // Try to read the first frame
            if (!socket.TryReceive(ref msg, timeout))
            {
                msg.Close();
                return false;
            }

            // We have one, so prepare the container
            if (frames == null)
                frames = new List<string>(expectedFrameCount);
            else
                frames.Clear();

            // Add the frame
            frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));

            // Rinse and repeat...
            while (msg.HasMore)
            {
                socket.Receive(ref msg);
                frames.Add(encoding.GetString(msg.Data, msg.Offset, msg.Size));
            }

            msg.Close();
            return true;
        }
コード例 #60
0
 /// <summary>
 /// Attempt to receive a single frame from <paramref name="socket"/>, then ignore its content.
 /// If no message is immediately available, return <c>false</c>.
 /// </summary>
 /// <param name="socket">The socket to receive from.</param>
 /// <returns><c>true</c> if a frame was received and ignored, otherwise <c>false</c>.</returns>
 public static bool TrySkipFrame( this IReceivingSocket socket)
 {
     var msg = new Msg();
     msg.InitEmpty();
     var received = socket.TryReceive(ref msg, TimeSpan.Zero);
     msg.Close();
     return received;
 }