System.Net.Sockets.UdpClient.BeginReceive C# (CSharp) Method

BeginReceive() public method

public BeginReceive ( AsyncCallback requestCallback, object state ) : IAsyncResult
requestCallback AsyncCallback
state object
return IAsyncResult
        public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
        {
            // Validate input parameters.
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            // Due to the nature of the ReceiveFrom() call and the ref parameter convention,
            // we need to cast an IPEndPoint to its base class EndPoint and cast it back down
            // to IPEndPoint.
            EndPoint tempRemoteEP;
            if (_family == AddressFamily.InterNetwork)
            {
                tempRemoteEP = IPEndPointStatics.Any;
            }
            else
            {
                tempRemoteEP = IPEndPointStatics.IPv6Any;
            }

            return _clientSocket.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
        }

Usage Example

Example #1
0
        private void thread()
        {
            UdpClient ucl = new UdpClient(6000);
            IAsyncResult iar = ucl.BeginReceive(null, null);

            while (!exit)
            {
                if (!iar.AsyncWaitHandle.WaitOne(1000))
                    continue;

                IPEndPoint ep = new IPEndPoint(0, 0);
                byte[] data = ucl.EndReceive(iar, ref ep);
                iar = ucl.BeginReceive(null, 0);

                using (MemoryStream ms = new MemoryStream(data))
                {
                    BinaryReader br = new BinaryReader(ms);

                    while (ms.Position < ms.Length)
                    {
                        CanMessage m = CanMessage.DeserializeFrom(br);

                        if (MessageReceived != null)
                            MessageReceived(this, m);
                    }
                }
            }

            ucl.Close();
        }
All Usage Examples Of System.Net.Sockets.UdpClient::BeginReceive