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; }
/// <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(); }
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); }
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(); }
public override void OnUnregistered() { base.OnUnregistered(); Debug.Assert(_zmqPredictedMotion != null); _zmqPredictedMotion.Close(); _msgRecv.Close(); _zmqPredictedMotion.Dispose(); _zmqPredictedMotion = null; _lastCenterEyePosition = Vector3.zero; }
public void Close() { if (_zmqPredictedMotion == null) { return; } _zmqPredictedMotion.Close(); _msgRecv.Close(); _zmqPredictedMotion.Dispose(); _zmqPredictedMotion = null; }
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; }
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; }
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; }
/// <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(); }
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(); } }
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); }
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); }
/// <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(); } }
/// <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(); }
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); }
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; }
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; }
/// <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; }
/// <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(); }
/// <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; }
/// <summary> /// Receive a single frame from <paramref name="socket"/>, asynchronously, and decode as a string using <paramref name="encoding"/>. /// </summary> /// <param name="socket">The socket to receive from.</param> /// <param name="encoding">The encoding used to convert the frame's data to a string.</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 as a string and boolean indicate if another frame of the same message follows..</returns> public static Task <(string, bool)> ReceiveFrameStringAsync( this NetMQSocket socket, 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 ? msg.GetString(encoding) : string.Empty; msg.Close(); return(Task.FromResult((str, msg.HasMore))); } TaskCompletionSource <(string, bool)> source = new TaskCompletionSource <(string, bool)>(); CancellationTokenRegistration?registration = null; if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(PropagateCancel); } void Listener(object sender, NetMQSocketEventArgs args) { if (socket.TryReceive(ref msg, TimeSpan.Zero)) { var str = msg.Size > 0 ? msg.GetString(encoding) : string.Empty; bool more = msg.HasMore; msg.Close(); socket.ReceiveReady -= Listener; registration?.Dispose(); source.TrySetResult((str, more)); } } void PropagateCancel() { socket.ReceiveReady -= Listener; registration?.Dispose(); source.TrySetCanceled(); } socket.ReceiveReady += Listener; return(source.Task); }
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; }
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; }
/// <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(); }
/// <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; }
/// <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; }
/// <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; }
/// <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; } } }
/// <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(); }
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; }
/// <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; }
/// <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(); }
/// <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; } } }
/// <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; }
/// <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; }
/// <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(); }
/// <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; }
/// <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; }
/// <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; }