EndReceiveFrom() public method

public EndReceiveFrom ( IAsyncResult asyncResult, EndPoint &endPoint ) : int
asyncResult IAsyncResult
endPoint System.Net.EndPoint
return int
Example #1
0
        private void End(IAsyncResult Ar)
        {
            var error = SocketError.Success;

            try
            {
                m_Socket.EndReceiveFrom(Ar, ref m_ReceiveEndPoint);
            }
            catch (SocketException e)
            {
                error = e.SocketErrorCode;
            }
            catch (ObjectDisposedException ode)
            {
                return;
            }

            m_Message.SetError(error);
            m_Message.SetEndPoint(m_ReceiveEndPoint);
            lock (m_ReceivePackages)
            {
                m_ReceivePackages.Add(m_Message);
            }
            Begin();
        }
Example #2
0
        private void EndReceiveFromCallback(System.IAsyncResult iar)
        {
            State state = iar.AsyncState as State;

            System.Net.Sockets.Socket socket = state.Socket;
            try
            {
                int    byteRead = socket.EndReceiveFrom(iar, ref state.RemoteEP);
                var    readbuf  = new byte[state.Buffer.Length];
                byte[] datasize = new byte[4];
                System.Array.Copy(state.Buffer, datasize, datasize.Length);
                int size = BitConverter.ToInt32(datasize, 0);
                if (size > 0)
                {
                    socket.BeginReceiveFrom(state.Buffer, 0, size, System.Net.Sockets.SocketFlags.None, ref state.RemoteEP, new System.AsyncCallback(this.EndReceiveFromCallback), state);
                }
                else
                {
                    System.Array.Copy(state.Buffer, readbuf, readbuf.Length);
                    this.UnPackage(readbuf);
                }
            }
            catch (Exception e)
            {
                LogerHelper.Loger.Error(e);
                this.RecOpen();
            }
        }
Example #3
0
        private async void StartUdpServer()
        {
            var udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            // Important to specify a timeout value, otherwise the socket ReceiveFrom() 
            // will block indefinitely if no packets are received and the thread will never terminate
            udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
            udpListener.Bind(new IPEndPoint(IPAddress.Any, 54321));

            var buffer = new byte[1500];
            EndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                var result = await Task.Factory.FromAsync(
               (iar, s) =>
                   udpListener.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref sender, iar,
                       null),
               iar => udpListener.EndReceiveFrom(iar, ref sender), null);
                if (result > 0)
                {
                    if (firstPacket == DateTime.MinValue)
                        firstPacket = DateTime.Now;

                    var data = new byte[result];
                    Buffer.BlockCopy(buffer, 0, data, 0, result);
                    ring.AddData(data);

                    Frame f = null;
                    do
                    {
                        f = ring.ReadFrame();
                        if (f != null)
                        {
                            f.Time = (DateTime.Now - firstPacket).TotalSeconds;
                            var ev = OnFrameReceived;
                            if (ev != null)
                            {
                                OnFrameReceived(this, new FrameReceivedEventArgs(f));
                            }
                        }
                    } while (f != null);

                }
            }
        }
Example #4
0
        private void Receive(Socket socket, EndPoint endPoint)
        {
            var data = new byte[socket.ReceiveBufferSize];
            socket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref endPoint, ar =>
            {
                if (DataReceived != null)
                {
                    var i = socket.EndReceiveFrom(ar, ref endPoint);
                    var data2 = new byte[i];
                    Array.Copy(data, data2, i);
                    var command = CommandBase.Parse(data2);

                    if (_debugLog != null)
                        _debugLog.WriteLine("Receive " + command.GetType().Name + "   Token: " + command.Token);

                    DataReceived(command);
                }
                Receive(socket, endPoint);
            }, null);
        }
Example #5
0
            /// <summary>
            /// Data received asynchronus result method, all client commands
            /// are processed through this asynchronus result method.
            /// </summary>
            /// <param name="ar">The current asynchronus result.</param>
            internal void DataReceiver(IAsyncResult ar)
            {
                try
                {
                    // Lock the socket receive process.
                    lock (Server.LockingSocket)
                    {
                        // Get the data from the client endpoint.
                        _dataReceiverBytesRead = _socket.EndReceiveFrom(ar, ref RemoteClient);
                    }

                    // Send a Received command to the server
                    // indicating that the client has data.
                    if (OnCommandSend != null)
                    {
                        OnCommandSend(this, "RECEIVED");
                    }
                }
                catch { }
            }
Example #6
0
        protected void OnReceiveUDP(IAsyncResult ar)
        {
            DateTime        dtReceive = DateTimePrecise.Now;
            BufferSocketRef objRef    = ar.AsyncState as BufferSocketRef;

            System.Net.EndPoint ep = (System.Net.EndPoint)m_tempRemoteEP;
            int nRecv = 0;

            try
            {
                nRecv = s.EndReceiveFrom(ar, ref ep);
                objRef.CheckInCopy(nRecv);
            }
            catch (SocketException e3) /// winso
            {
                objRef.CheckInCopy(nRecv);
                LogError(MessageImportance.High, "EXCEPTION", e3.ToString());

                /// Get 10054 if the other end is not listening (ICMP returned)... fixed above with IOControl
                if (e3.ErrorCode != 10054)
                {
                }
                return;
            }
            catch (ObjectDisposedException e4) // socket was closed
            {
                objRef.CheckInCopy(nRecv);
                this.LogWarning(MessageImportance.Low, "EXCEPTION", e4.ToString());
                return;
            }
            catch (Exception e5)
            {
                objRef.CheckInCopy(nRecv);
                LogError(MessageImportance.High, "EXCEPTION", e5.ToString());
                return;
            }

            System.Net.IPEndPoint ipep = (System.Net.IPEndPoint)ep;
            OnRecv(objRef.bRecv, nRecv, ipep, dtReceive);
        }
Example #7
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)ar.AsyncState;
            Int32 read = 0;

            try
            {
                EndPoint remoteEP = Socket.RemoteEndPoint;
                read = socket.EndReceiveFrom(ar, ref remoteEP);
            }
            catch (ObjectDisposedException)
            {
                // do nothing
                return;
            }
            catch (Exception ex)
            {
                EndReceive(ex);
                return;
            }

            if (read > 0)
            {
                if (ReuseBuffer)
                {
                    EndReceive(IoBuffer.Wrap(_readBuffer, 0, read));
                }
                else
                {
                    IoBuffer buf = IoBuffer.Allocate(read);
                    buf.Put(_readBuffer, 0, read);
                    buf.Flip();
                    EndReceive(buf);
                }
                return;
            }

            // closed
            Processor.Remove(this);
        }
Example #8
0
        public byte[] EndReceive(IAsyncResult asyncResult, out IPEndPoint endPoint)
        {
            MyAsyncResult receiveAsyncResult = asyncResult as MyAsyncResult;

            if (receiveAsyncResult == null)
            {
                throw new ArgumentException("Invalid Async Result", "asyncResult");
            }

            int length = _socket.EndReceiveFrom(receiveAsyncResult.AsyncResult, ref receiveAsyncResult.EndPoint);

            endPoint = receiveAsyncResult.EndPoint as IPEndPoint;

            if (length == 65535)
            {
                return(receiveAsyncResult.Buffer);
            }
            else
            {
                byte[] result = new byte[length];
                Buffer.BlockCopy(receiveAsyncResult.Buffer, 0, result, 0, length);
                return(result);
            }
        }
        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;
        }
Example #10
0
        public void NetworkTargetUdpTest()
        {
            var target = new NetworkTarget()
            {
                Address = "udp://127.0.0.1:3002",
                Layout = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                Exception receiveException = null;
                var receivedMessages = new List<string>();
                var receiveFinished = new ManualResetEvent(false);

                byte[] receiveBuffer = new byte[4096];

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
                EndPoint remoteEndPoint = null;
                AsyncCallback receivedDatagram = null;

                receivedDatagram = result =>
                    {
                        try
                        {
                            int got = listener.EndReceiveFrom(result, ref remoteEndPoint);
                            string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
                            lock (receivedMessages)
                            {
                                receivedMessages.Add(message);
                                if (receivedMessages.Count == 100)
                                {
                                    receiveFinished.Set();
                                }
                            }

                            remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                            listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
                        }
                        catch (Exception ex)
                        {
                            receiveException = ex;
                        }
                    };

                remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions = new List<Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                            pendingWrites--;
                            if (pendingWrites == 0)
                            {
                                writeCompleted.Set();
                            }
                        }
                    };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "message" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(30000, false));
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(30000, false));
                Assert.AreEqual(toWrite, receivedMessages.Count);
                for (int i = 0; i < toWrite; ++i)
                {
                    Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
                }

                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
            }
        }
Example #11
0
 int Utils.Wrappers.Interfaces.ISocket.EndReceiveFrom(System.IAsyncResult asyncResult, ref System.Net.EndPoint endPoint)
 {
     return(InternalSocket.EndReceiveFrom(asyncResult, ref endPoint));
 }
Example #12
0
        ////廣播3
        private void ReceiveCallback(IAsyncResult iar)
        {
            EndPoint remoteEnd = new IPEndPoint(IPAddress.Any, Int32.Parse(control.udp_port));
            sock = (Socket)iar.AsyncState;
            int received = sock.EndReceiveFrom(iar, ref remoteEnd);
            byte[] localMsg = new byte[received];
            Array.Copy(getdata, localMsg, received);
            var input = Encoding.UTF8.GetString(localMsg, 0, received);
            var inn = "UDP=" + input;

            _logger.Info(inn);

            input = input.Replace("\a", "");
            input = input.Replace("\r\n", string.Empty);
            analysis_type(input);

            sock.BeginReceiveFrom(getdata, 0, getdata.Length, SocketFlags.None, ref remoteEnd, new AsyncCallback(ReceiveCallback), sock);
        }
Example #13
0
File: UDP.cs Project: dzamkov/DUIP
        private void _Receive(Socket Socket, byte[] Buffer)
        {
            while (true)
            {
                try
                {
                    const int offset = 0;
                    EndPoint endpoint = new IPEndPoint(Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
                    Socket.BeginReceiveFrom(Buffer, offset, Buffer.Length, SocketFlags.None, ref endpoint, delegate(IAsyncResult ar)
                    {
                        try
                        {
                            int size = Socket.EndReceiveFrom(ar, ref endpoint);
                            if (this.Received != null)
                            {
                                this.Received((IPEndPoint)endpoint, new BufferData(Buffer).GetPartion(0, size));
                            }
                        }
                        catch (SocketException se)
                        {
                            if (!_CanIgnore(se))
                            {
                                throw se;
                            }
                        }

                        // Restart receive cycle
                        this._Receive(Socket, Buffer);
                    }, null);
                    return;
                }
                catch (SocketException se)
                {
                    if (!_CanIgnore(se))
                    {
                        throw se;
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Data received asynchronus result method, all client commands
        /// are processed through this asynchronus result method.
        /// </summary>
        /// <param name="ar">The current asynchronus result.</param>
        internal void DataReceiver(IAsyncResult ar)
        {
            try
            {
                // Clear the last error.
                ClearLastError();

                // Lock the socket receive process.
                lock (ServerRef.LockingSocket)
                {
                    // Get the data from the client endpoint.
                    _dataReceiverBytesRead = _socket.EndReceiveFrom(ar, ref RemoteClient);
                }

                // Send a Received command to the server
                // indicating that the client has data.
                if (OnCommandSend != null)
                {
                    OnCommandSend(this, "RECEIVED");
                }

                // Make sure only one thread at a time is adding to the buffer.
                lock (_lockReceiver)
                {
                    // Make sure data has arrived.
                    if (_dataReceiverBytesRead > 0)
                    {
                        // If the upper capacity of the buffer
                        // has been reached then stop writting
                        // until the request buffer gets to the
                        // lower capacity threshold.
                        if (_requestBuffer.IsUpperCapacityPercentage())
                        {
                            // Create the tasks.
                            Task[] tasks = new Task[1];
                            Interlocked.Exchange(ref _exitWaitReceiveIndicator, 0);

                            try
                            {
                                // Write to the request stream task.
                                Task readFromStream = Task.Factory.StartNew(() =>
                                {
                                    // Create a new spin wait.
                                    SpinWait sw = new SpinWait();

                                    // Action to perform.
                                    while (Interlocked.CompareExchange(ref _exitWaitReceiveIndicator, 0, 1) == 0)
                                    {
                                        // The NextSpinWillYield property returns true if
                                        // calling sw.SpinOnce() will result in yielding the
                                        // processor instead of simply spinning.
                                        if (sw.NextSpinWillYield)
                                        {
                                            // If the buffer is below the lower capacity
                                            // threshold then exist the spin wait.
                                            if (!_requestBuffer.IsLowerCapacityPercentage())
                                            {
                                                Interlocked.Exchange(ref _exitWaitReceiveIndicator, 1);
                                            }
                                        }

                                        // Performs a single spin.
                                        sw.SpinOnce();
                                    }
                                });

                                // Assign the listener task.
                                tasks[0] = readFromStream;

                                // Wait for all tasks to complete.
                                Task.WaitAll(tasks);
                            }
                            catch { }

                            // For each task.
                            foreach (Task item in tasks)
                            {
                                try
                                {
                                    // Release the resources.
                                    item.Dispose();
                                }
                                catch { }
                            }
                            tasks = null;
                        }

                        // Write to the request stream.
                        _requestStream.WriteToStream(_readBuffer, 0, _dataReceiverBytesRead);

                        // Set the timeout on first receive.
                        SetTimeOut();

                        if (_context != null)
                        {
                            // Assign the new client IP endpoint.
                            _context.RemoteEndPoint = GetClientIPEndPoint();
                        }
                    }
                }

                // Make sure data has arrived.
                if (_dataReceiverBytesRead > 0)
                {
                    // Make sure the context exists.
                    if (_context != null)
                    {
                        // If not in async mode.
                        if (!_context.IsAsyncMode)
                        {
                            // Allow an active context.
                            if (Interlocked.CompareExchange(ref _isContextActive, 1, 0) == 0)
                            {
                                // Set the active context indicator to true
                                // no other context can start.
                                Interlocked.Exchange(ref _isContextActive, 1);

                                // Received the request from the client.
                                // Send the message context.
                                Receiver();
                            }
                        }
                        else
                        {
                            // If the data available handler has been set
                            // then send a trigger indicating that
                            // data is available.
                            if (_context.ReceivedAsyncMode != null)
                            {
                                // Allow an active context.
                                if (Interlocked.CompareExchange(ref _isAsyncModeActive, 1, 0) == 0)
                                {
                                    // Set the active context indicator to true
                                    // no other context can start.
                                    Interlocked.Exchange(ref _isAsyncModeActive, 1);

                                    // Received the request from the client.
                                    // Send the message context.
                                    AsyncModeReceiver();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetLastError(ex);
            }
        }