private byte[] Receive(SendRecvFlags flags) { IntPtr buffer = IntPtr.Zero; int rc = Interop.nn_recv(_socket, ref buffer, Constants.NN_MSG, (int)flags); if (rc < 0 || buffer == null) { return(null); } byte[] output = new byte[rc]; try { Marshal.Copy(buffer, output, 0, rc); } finally { rc = Interop.nn_freemsg(buffer); if (rc != 0) { throw new NanomsgException("freemsg"); } } return(output); }
/// <summary> /// Receives a message of unknown length into a new buffer. /// </summary> /// <returns> /// The error code from nn_freemsg. Should always be 0. Probably safe to ignore. /// </returns> /// <remarks> /// This is a bit inefficient at the moment. /// </remarks> public static int Recv(int s, out byte[] buf, SendRecvFlags flags) { IntPtr buffer = IntPtr.Zero; int rc = Interop.nn_recv(s, ref buffer, Constants.NN_MSG, (int)flags); if (rc < 0) { buf = null; return(rc); } int numberOfBytes = rc; // this inefficient, I'm sure there must be a better way. buf = new byte[numberOfBytes]; for (int i = 0; i < numberOfBytes; ++i) { buf[i] = Marshal.ReadByte(buffer, i); } int rc_free = Interop.nn_freemsg(buffer); Debug.Assert(rc_free == 0); return(rc); }
private NanomsgReadStream ReceiveStream(SendRecvFlags flags) { IntPtr buffer = IntPtr.Zero; int rc = Interop.nn_recv(_socket, ref buffer, Constants.NN_MSG, (int)flags); if (rc < 0 || buffer == null) { return(null); } /* * In order to prevent managed allocations per receive, we attempt to recycle stream objects. This * will work optimally if the stream is disposed before the next receive call, as in this case each * socket class will always reuse the same stream. * * Disposing the stream will both release its nanomsg-allocated native buffer and return it to its * socket class for reuse. */ var stream = Interlocked.Exchange(ref _recycledReadStream, null); if (stream != null) { stream.Reinitialize(buffer, rc); } else { stream = new NanomsgReadStream(buffer, rc, _freeReadDisposer ?? (_freeReadDisposer = new NanomsgNativeDisposer() { Socket = (NanomsgSocketBase)this })); } return(stream); }