示例#1
0
 private void EndReceiveFrom(IAsyncResult ir)
 {
     if (IsListening)
     {
         UdpState state = ir.AsyncState as UdpState;
         try
         {
             if (ir.IsCompleted)
             {
                 int    length     = state.Socket.EndReceiveFrom(ir, ref state.Remote);
                 byte[] btReceived = new byte[length];
                 Buffer.BlockCopy(state.Buffer, 0, btReceived, 0, length);
                 OnReceived(new UdpEventArgs(btReceived, state.Remote));
             }
         }
         catch (Exception ex)
         {
             System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message + ex.Source);
         }
         finally
         {
             state.Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
         }
     }
 }
示例#2
0
        public void Listening()
        {
            IPAddress ip = IPAddress.Any;

            try
            {
                if (this._ip != null)
                {
                    if (!IPAddress.TryParse(this._ip, out ip))
                    {
                        throw new ArgumentException("IP地址错误", "Ip");
                    }
                }
                _sck.Bind(new IPEndPoint(ip, this._port));

                UdpState state = new UdpState();
                state.Socket = _sck;
                state.Remote = new IPEndPoint(IPAddress.Any, 0);
                _sck.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);

                IsListening = true;
            }
            catch (ArgumentException ex)
            {
                IsListening = false;
                System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
                throw ex;
            }
            catch (Exception ex)
            {
                IsListening = false;
                System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
                throw ex;
            }
        }