private void EndReceive(IAsyncResult result)
        {
            UDPServiceAsyncState state = (UDPServiceAsyncState)result.AsyncState;
            int      dataLength;
            EndPoint clientip = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                dataLength = Socket.EndReceiveFrom(result, ref clientip);
            }
            catch
            {
                dataLength = 0;
            }
            byte[] data = state.Data;

            if (dataLength == 0)
            {
                return;
            }

            EndPoint ip = new IPEndPoint(IPAddress.Any, 0);

            state.Data = new byte[ReceiveBufferSize];
            Socket.BeginReceiveFrom(state.Data, 0, ReceiveBufferSize, SocketFlags.None, ref ip, EndReceive, state);

            if (ReceiveCompleted != null)
            {
                ReceiveCompleted(this, new UDPServiceEventArgs {
                    EndPoint = (IPEndPoint)clientip, Data = data, DataLength = dataLength, Operation = SocketAsyncOperation.ReceiveFrom
                });
            }
        }
        private void CreateReceive()
        {
            UDPServiceAsyncState state = new UDPServiceAsyncState();

            state.Data = new byte[ReceiveBufferSize];
            EndPoint ip = new IPEndPoint(IPAddress.Any, 0);

            Socket.BeginReceiveFrom(state.Data, 0, ReceiveBufferSize, SocketFlags.None, ref ip, EndReceive, state);
        }
        private void EndSend(IAsyncResult result)
        {
            UDPServiceAsyncState state = (UDPServiceAsyncState)result.AsyncState;

            Socket.EndSendTo(result);

            if (state.IsAsync && SendCompleted != null)
            {
                SendCompleted(this, new UDPServiceEventArgs {
                    EndPoint = state.EndPoint, Data = state.Data, DataLength = state.Data.Length, Operation = SocketAsyncOperation.SendTo
                });
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="remote">远程终结点。</param>
        /// <param name="data">要发送的数据。</param>
        public void SendAsync(IPEndPoint remote, byte[] data)
        {
            if (!IsStarted)
            {
                throw new InvalidOperationException("没有开始服务。");
            }
            UDPServiceAsyncState state = new UDPServiceAsyncState();

            state.Data     = data;
            state.IsAsync  = true;
            state.EndPoint = remote;
            Socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, remote, EndSend, state);
        }