Ejemplo n.º 1
0
        /// <summary>
        /// This is where all the actual 'listening' is done.
        /// </summary>
        protected void Listen()
        {
            if (Session == null)
            {
                throw new NullReferenceException("This IListener has no Session yet!");
            }

            IPEndPoint remoteEndPoint;

            if (_endpoint == "ANY")
            {
                remoteEndPoint = new IPEndPoint(IPAddress.Any, _port);
            }
            else
            {
                remoteEndPoint = new IPEndPoint(IPAddress.Parse(_endpoint), _port);
            }

            byte[] buffer;
            string loggingEvent;

            _hexEncoder = new HexEncoder();
            try
            {
                _udpClient = new UdpClient(_port);

                _log.Info(GetHashCode(), "Started listening for UDP on port " + _port.ToString() + " using prefix: " + MessagePrefix);

                while (true)
                {
                    buffer = _udpClient.Receive(ref remoteEndPoint);

                    var sender = "";
                    if (Session.Viewer.ShowListenerPrefix)
                    {
                        sender = remoteEndPoint.Address.ToString() + " ";
                    }

                    if (_encName == HexEncoder.EncName)
                    {
                        loggingEvent = sender + _hexEncoder.GetHex(_address, buffer);
                        _address    += (ulong)buffer.Length;
                    }
                    else
                    {
                        loggingEvent = sender + Encoding.GetEncoding(_encName).GetString(buffer);
                    }
                    Session.AddEvent(this, loggingEvent);
                }
            }
            catch (SocketException ex)
            {
                var foo = "(UDP ERROR) The UDP listener could not be started at port " + _port.ToString() + " " + Environment.NewLine + ex.Message;
                _log.Error(GetHashCode(), foo);
                Session.AddEvent(this, foo);
            }
            catch (ThreadAbortException)
            {
                var foo = "(UDP) UdpListener thread aborted.";
                _log.Error(GetHashCode(), foo);
                Session.AddEvent(this, foo);
            }
            catch (Exception e)
            {
                var foo = "(UDP ERROR) Internal error in UdpListener: " + e.Message + Environment.NewLine + e.StackTrace;
                _log.Error(GetHashCode(), foo);
                Session.AddEvent(this, foo);
            }
            finally
            {
                if (_udpClient != null)
                {
                    _udpClient.Close();
                }
            }
        }