Ejemplo n.º 1
0
        public void Send(Message message)
        {
            base.ThrowIfDisposedOrNotOpen();

            ArraySegment <byte> messageBuffer = EncodeMessage(message);

            // Adding the framing header
            messageBuffer = FramingCodec.Encode(this.remoteAddress.Uri,
                                                messageBuffer, parent.BufferManager);

            try
            {
                int bytesSent = this.socket.SendTo(messageBuffer.Array, messageBuffer.Offset, messageBuffer.Count,
                                                   SocketFlags.None, this.remoteEndPoint);

                if (bytesSent != messageBuffer.Count)
                {
                    throw new CommunicationException(string.Format(CultureInfo.CurrentCulture,
                                                                   "A Udp error occurred sending a message to {0}.", this.remoteEndPoint));
                }
            }
            catch (SocketException socketException)
            {
                throw UdpChannelHelpers.ConvertTransferException(socketException);
            }
            finally
            {
                // Must make sure buffers are always returned to the BufferManager
                parent.BufferManager.ReturnBuffer(messageBuffer.Array);
            }
        }
Ejemplo n.º 2
0
        FramingData EndReceive(Socket listenSocket, IAsyncResult result)
        {
            // if we've started the shutdown process, then we've disposed
            // the socket and calls to socket.EndReceive will throw
            if (closed)
            {
                return(null);
            }

            byte[] buffer = ((SocketReceiveState)result.AsyncState).Buffer;
            Debug.Assert(buffer != null);
            FramingData data = null;

            try
            {
                int count = 0;

                lock (ThisLock)
                {
                    // if we've started the shutdown process, socket is disposed
                    // and calls to socket.EndReceive will throw
                    if (!closed)
                    {
                        EndPoint dummy = CreateDummyEndPoint(listenSocket);
                        count = listenSocket.EndReceiveFrom(result, ref dummy);
                    }
                }

                if (count > 0)
                {
                    data = FramingCodec.Decode(new ArraySegment <byte>(buffer, 0, count));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error in completing the async receive via EndReceiveFrom method.");
                Debug.WriteLine(e.ToString());
            }
            finally
            {
                if (data == null)
                {
                    this.bufferManager.ReturnBuffer(buffer);
                    buffer = null;
                }
            }

            return(data);
        }