A Msg struct is the lowest-level interpretation of a ZeroMQ message, and simply contains byte-array data and MsgType and MsgFlags properties. It supports message buffer pooling.
Many users will not use this class directly. However in high-performance situations it may be useful. When used correctly it's possible to have zero-copy and zero-allocation behaviour.
Ejemplo n.º 1
0
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: remote_thr <connect-to> <message-size> <message-count>");
                return 1;
            }

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

            using (var context = NetMQContext.Create())
            using (var push = context.CreatePushSocket())
            {
                push.Connect(connectTo);

                for (int i = 0; i != messageCount; i++)
                {
                    var msg = new Msg();
                    msg.InitPool(messageSize);
                    push.Send(ref msg, SendReceiveOptions.None);
                    msg.Close();
                }
            }

            return 0;
        }
Ejemplo n.º 2
0
    public bool sendAndReceive(ref NetMQMessage req_msg, ref NetMQ.Msg resp_msg)
    {
        if (socket == null)
        {
            reconnect();
        }

        bool         ok   = false;
        NetMQMessage copy = new NetMQMessage(req_msg);

        socket.SendMultipartMessage(copy);

        // receive
        if (socket.TryReceive(ref resp_msg, timeout))
        {
            ok = true;
            //UnityEngine.Debug.Log("ReliableExternalClient: response received "
            //    + new StdMessage(resp_msg.Data[1], resp_msg.Data[2]).to_string());
        }

        copy.Clear();
        socket.Dispose();
        socket.Close();
        socket = null;
        if (socket == null)
        {
            UnityEngine.Debug.Log("ReliableExternalClient: socket closed and null");
        }

        return(ok);
    }
Ejemplo n.º 3
0
 /// <summary>
 /// Transmit a byte-array of data over this socket, block until frame is sent.
 /// </summary>
 /// <param name="socket">the IOutgoingSocket to transmit on</param>
 /// <param name="data">the byte-array of data to send</param>
 /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
 /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
 public static void SendFrame( this IOutgoingSocket socket,  byte[] data, int length, bool more = false)
 {
     var msg = new Msg();
     msg.InitPool(length);
     Buffer.BlockCopy(data, 0, msg.Data, msg.Offset, length);
     socket.Send(ref msg, more);
     msg.Close();
 }
Ejemplo n.º 4
0
    public bool sendAndReceive(ref NetMQ.Msg req_msg, ref NetMQ.Msg resp_msg)
    {
        if (socket == null)
        {
            reconnect();
        }

        StdMessage m = new StdMessage(req_msg.Data[1], req_msg.Data[2]);

        NetMQ.Msg copy = new NetMQ.Msg();
        bool      ok   = false;

        for (uint i = 0; i < retries; i++)
        {
            copy.Copy(ref req_msg);

            // send
            if (!socket.TrySend(ref copy, TimeSpan.FromMilliseconds(min_trysend_ms), false))
            {
                ok = false;
                UnityEngine.Debug.Log("ReliableExternalClient: could not send");
                break;

                //TODO: clear enqueued messages when server is offline
            }
            //UnityEngine.Debug.Log("ReliableExternalClient: request sent " + m.to_string());

            // receive
            if (socket.TryReceive(ref resp_msg, timeout))
            {
                ok = true;
                // UnityEngine.Debug.Log("ReliableExternalClient: response received "
                //+ new StdMessage(resp_msg.Data[1], resp_msg.Data[2]).to_string());
                break;
            }

            //UnityEngine.Debug.Log(String.Format("ReliableExternalClient: no response from server {0}. Retrying", srvAddress));
            reconnect();
        }

        if (!ok)
        {
            UnityEngine.Debug.Log(String.Format("ReliableExternalClient: server {0} seems to be offline. Abandoning", srvAddress));
        }

        copy.Close();
        socket.Dispose();  //call Dispose on all sockets before cleanup the netmq context
        socket.Close();

        socket = null;

        if (socket == null)
        {
            UnityEngine.Debug.Log("ReliableExternalClient: socket closed and null");
        }

        return(ok);
    }
Ejemplo n.º 5
0
        public void Register()
        {
            NetMQ.Msg msg = new NetMQ.Msg();
            msg.InitGC(new byte[] { 1 }, 1);
            _socket.TrySend(ref msg, TimeSpan.FromMilliseconds(100), false);
            _state = MachineState.Registered;
#if DEBUG
            //GetProgramData();
#endif
        }
Ejemplo n.º 6
0
 public void Heartbeat()
 {
     if (DateTime.Now - _lastHeart > TimeSpan.FromMilliseconds(100))
     {
         NetMQ.Msg msg = new NetMQ.Msg();
         msg.InitGC(new byte[] { 2 }, 1);
         _socket.TrySend(ref msg, TimeSpan.FromMilliseconds(100), false);
         _lastHeart = DateTime.Now;
     }
 }
    private void Awake()
    {
        _msg = new NetMQ.Msg();

        cameraRig         = GetComponent <AirVRCameraRig>();
        _foveatedRenderer = GetComponent <OCSVRWorksCameraRig>();

        liveMotionProvider      = new MPPLiveMotionDataProvider();
        predictedMotionProvider = new AirXRPredictedMotionProvider(this, liveMotionProvider);
        gameEventEmitter        = new AirXRGameEventEmitter(cameraRig);
    }
Ejemplo n.º 8
0
        public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, SendReceiveOptions options)
        {
            var msg = new Msg();
            msg.InitPool(length);

            Buffer.BlockCopy(data, 0, msg.Data, 0, length);

            socket.Send(ref msg, options);

            msg.Close();
        }
Ejemplo n.º 9
0
    public NetMQ.Msg to_Msg()
    {
        NetMQ.Msg msg       = new NetMQ.Msg();
        byte[]    msg_bytes = new byte[3] {
            airt, module, action
        };

        msg.InitPool(msg_bytes.Length);  // num of bytes
        msg.Put(msg_bytes, 0, msg_bytes.Length);

        return(msg);
    }
    public void Connect(string endpoint)
    {
        if (_owner.bypassPrediction || _zmqPredictedMotion != null)
        {
            return;
        }

        _zmqPredictedMotion = new PullSocket();
        _zmqPredictedMotion.Connect(endpoint);

        _msgRecv = new NetMQ.Msg();
        _msgRecv.InitPool(8 + 4 * 4);
    }
Ejemplo n.º 11
0
        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 msg = new Msg();
                msg.InitEmpty();

                pullSocket.Receive(ref msg);

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

                msg.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);
            }

            return 0;
        }
Ejemplo n.º 12
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;
        }
Ejemplo n.º 13
0
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: remote_lat remote_lat <connect-to> <message-size> <roundtrip-count>");
                return 1;
            }

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

            using (var context = NetMQContext.Create())
            using (var req = context.CreateRequestSocket())
            {
                req.Connect(connectTo);

                var msg = new Msg();
                msg.InitPool(messageSize);

                var stopWatch = Stopwatch.StartNew();

                for (int i = 0; i != roundtripCount; i++)
                {
                    req.Send(ref msg, SendReceiveOptions.None);

                    req.Receive(ref msg);

                    if (msg.Size != messageSize)
                    {
                        Console.WriteLine("message of incorrect size received. Received: {0} Expected: {1}", msg.Size, messageSize);
                        return -1;
                    }
                }

                stopWatch.Stop();

                msg.Close();

                double elapsedMicroseconds = stopWatch.ElapsedTicks*1000000L/Stopwatch.Frequency;
                double latency = elapsedMicroseconds/(roundtripCount*2);

                Console.WriteLine("message size: {0} [B]", messageSize);
                Console.WriteLine("roundtrip count: {0}", roundtripCount);
                Console.WriteLine("average latency: {0:0.000} [µs]", latency);
            }

            return 0;
        }
    public override void OnRegistered(byte inDeviceID, string arguments)
    {
        base.OnRegistered(inDeviceID, arguments);

        Arguments args = JsonUtility.FromJson <Arguments>(arguments);

        Debug.Assert(string.IsNullOrEmpty(args.PredictedMotionOutputEndpoint) == false);
        Debug.Assert(_zmqPredictedMotion == null);

        _zmqPredictedMotion = new PullSocket();
        _zmqPredictedMotion.Connect(args.PredictedMotionOutputEndpoint);

        _msgRecv = new NetMQ.Msg();
        _msgRecv.InitPool(8 + 4 * 4);
    }
Ejemplo n.º 15
0
        /// <summary>
        /// Transmit a string over this socket, block until frame is sent.
        /// </summary>
        /// <param name="socket">the IOutgoingSocket to transmit on</param>
        /// <param name="message">the string to send</param>
        /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
        public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool more = false)
        {
            var msg = new Msg();

            // Count the number of bytes required to encode the string.
            // Note that non-ASCII strings may not have an equal number of characters
            // and bytes. The encoding must be queried for this answer.
            // With this number, request a buffer from the pool.
            msg.InitPool(SendReceiveConstants.DefaultEncoding.GetByteCount(message));

            // Encode the string into the buffer
            SendReceiveConstants.DefaultEncoding.GetBytes(message, 0, message.Length, msg.Data, 0);

            socket.Send(ref msg, more);
            msg.Close();
        }
Ejemplo n.º 16
0
        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;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Attempt to transmit a single frame on <paramref cref="socket"/>.
        /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
        /// </summary>
        /// <param name="socket">the IOutgoingSocket to transmit on</param>
        /// <param name="timeout">The maximum period of time to try to send a message.</param>
        /// <param name="data">the byte-array of data to send</param>        
        /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
        /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
        /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
        public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] byte[] data, int length, bool more = false)
        {
            var msg = new Msg();
            msg.InitPool(length);
            Buffer.BlockCopy(data, 0, msg.Data, 0, length);

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

            msg.Close();
            return true;
        }
Ejemplo n.º 18
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;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Block until the message can be sent.
        /// </summary>
        /// <remarks>
        /// The call  blocks until the message can be sent and cannot be interrupted.
        /// Whether the message can be sent depends on the socket type.
        /// </remarks>
        /// <param name="socket">The socket to send the message on.</param>
        /// <param name="msg">An object with message's data to send.</param>
        /// <param name="more">Indicate if another frame is expected after this frame</param>
        public static void Send(this IOutgoingSocket socket, ref Msg msg, bool more)
        {
            var result = socket.TrySend(ref msg, SendReceiveConstants.InfiniteTimeout, more);

            Debug.Assert(result);
        }
Ejemplo n.º 20
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;
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Block until the next message arrives, then make the message's data available via <paramref name="msg"/>.
 /// </summary>
 /// <remarks>
 /// The call  blocks until the next message arrives, and cannot be interrupted. This a convenient and safe when
 /// you know a message is available, such as for code within a <see cref="NetMQSocket.ReceiveReady"/> callback.
 /// </remarks>
 /// <param name="socket">The socket to receive from.</param>
 /// <param name="msg">An object to receive the message's data into.</param>
 public static void Receive(this IReceivingSocket socket, ref Msg msg)
 {
     var result = socket.TryReceive(ref msg, SendReceiveConstants.InfiniteTimeout);
     Debug.Assert(result);
 }
Ejemplo n.º 22
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();
        }
Ejemplo n.º 23
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;
        }
Ejemplo n.º 24
0
 // utils
 public static bool isStdNotification(ref NetMQ.Msg m)
 {
     return(m.Data[0] == (byte)'A' && m.Data[1] == (byte)Modules.STD_NOTIFICATIONS_MODULE);
 }
Ejemplo n.º 25
0
 public static byte getMessageAirtSignature(ref NetMQ.Msg m)
 {
     return(m.Data[0]);
 }
Ejemplo n.º 26
0
 public static byte getMessageModule(ref NetMQ.Msg m)
 {
     return((byte)(m.Data[1] & 0x7F));
 }
Ejemplo n.º 27
0
 public static byte getMessageAction(ref NetMQ.Msg m)
 {
     return(m.Data[2]);
 }
Ejemplo n.º 28
0
 // constructor
 public StdMessage(ref NetMQ.Msg m)
     : base(m.Data[1], m.Data[2])
 {
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Transmit a status-signal over this socket.
        /// </summary>
        /// <param name="socket">the IOutgoingSocket to transmit on</param>
        /// <param name="status">a byte that contains the status signal to send</param>
        private static void Signal([NotNull] this IOutgoingSocket socket, byte status)
        {
            long signalValue = 0x7766554433221100L + status;

            Msg msg = new Msg();
            msg.InitPool(8);
            NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data);

            socket.Send(ref msg, false);

            msg.Close();
        }
Ejemplo n.º 30
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;
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Send a message if one is available within <paramref name="timeout"/>.
 /// </summary>
 /// <param name="msg">An object with message's data to send.</param>
 /// <param name="timeout">The maximum length of time to try and send a message. If <see cref="TimeSpan.Zero"/>, no
 /// wait occurs.</param>
 /// <param name="more">Indicate if another frame is expected after this frame</param>
 /// <returns><c>true</c> if a message was sent, otherwise <c>false</c>.</returns>
 public virtual bool TrySend(ref Msg msg, TimeSpan timeout, bool more)
 {
     return(m_socketHandle.TrySend(ref msg, timeout, more));
 }
Ejemplo n.º 32
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;
        }
Ejemplo n.º 33
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();
 }
Ejemplo n.º 34
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;
        }
Ejemplo n.º 35
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;
        }
Ejemplo n.º 36
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;
        }
Ejemplo n.º 37
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;
 }
Ejemplo n.º 38
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;
        }
Ejemplo n.º 39
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;
 }
Ejemplo n.º 40
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;
        }
Ejemplo n.º 41
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;
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Block until the message is can be sent.
 /// </summary>
 /// <remarks>
 /// The call  blocks until the message can be sent and cannot be interrupted. 
 /// Wether the message can be sent depends on the socket type.
 /// </remarks>
 /// <param name="socket">The socket to send the message on.</param>
 /// <param name="msg">An object with message's data to send.</param>
 /// <param name="more">Indicate if another frame is expected after this frame</param>
 public static void Send(this IOutgoingSocket socket, ref Msg msg, bool more)
 {
     var result = socket.TrySend(ref msg, SendReceiveConstants.InfiniteTimeout, more);
     Debug.Assert(result);
 }
Ejemplo n.º 43
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();
 }
Ejemplo n.º 44
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();
 }
Ejemplo n.º 45
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;
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Attempt to transmit a status-signal over this socket.
        /// If signal cannot be sent immediately, return <c>false</c>.
        /// </summary>
        /// <param name="socket">the IOutgoingSocket to transmit on</param>
        /// <param name="status">a byte that contains the status signal to send</param>
        private static bool TrySignal([NotNull] this IOutgoingSocket socket, byte status)
        {
            long signalValue = 0x7766554433221100L + status;

            Msg msg = new Msg();
            msg.InitPool(8);
            NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data);

            if (!socket.TrySend(ref msg, TimeSpan.Zero, false))
            {
                msg.Close();
                return false;
            }

            msg.Close();
            return true;
        }
Ejemplo n.º 47
0
 /// <summary>Attempt to receive a message for the specified amount of time.</summary>
 /// <param name="msg">A reference to a <see cref="Msg"/> instance into which the received message
 /// data should be placed.</param>
 /// <param name="timeout">The maximum amount of time the call should wait for a message before returning.</param>
 /// <returns><c>true</c> if a message was received before <paramref name="timeout"/> elapsed,
 /// otherwise <c>false</c>.</returns>
 public virtual bool TryReceive(ref Msg msg, TimeSpan timeout)
 {
     return(m_socketHandle.TryRecv(ref msg, timeout));
 }