/// <summary>
        /// This is the thread where the socket server will accept client connections and process
        /// </summary>
        protected void WaitForConnections()
        {
            EndPoint sender = null;

            byte[]    buffer        = null;
            ArrayList previousBytes = new ArrayList();
            int       bytesRead     = 0;
            byte      mType         = 0;
            UInt16    mId           = 0;

            byte[] udpMsg  = null;
            int    maxSize = AbstractNetworkUtils.GetMaxMessageSize();

            while (!this._isDone)
            {
                try
                {
                    if (this._socket.Available >= 4 /*Min size of CoAP block*/)
                    {
                        sender    = new IPEndPoint(IPAddress.Any, 0);
                        buffer    = new byte[maxSize * 2];
                        bytesRead = this._socket.ReceiveFrom(buffer, ref sender);
                        udpMsg    = new byte[bytesRead];
                        Array.Copy(buffer, udpMsg, bytesRead);

                        mType = AbstractCoAPMessage.PeekMessageType(udpMsg);
                        mId   = AbstractCoAPMessage.PeekMessageID(udpMsg);

                        if ((mType == CoAPMessageType.CON ||
                             mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg))
                        {
                            this.ProcessRequestMessageReceived(udpMsg, ref sender);
                        }
                        else
                        {
                            this.ProcessResponseMessageReceived(udpMsg, ref sender);
                        }
                    }
                    else
                    {
                        //Nothing on the socket...wait
                        Thread.Sleep(5000);
                    }
                }
                catch (SocketException se)
                {
                    //Try to re-initialize socket, and proceed only when the socket
                    //is successfully re-initialized
                    this._isDone = !this.ReInitSocket();
                    this.HandleError(se, null);
                }
                catch (ArgumentNullException argEx)
                {
                    if (mType == CoAPMessageType.CON)
                    {
                        this.RespondToBadCONRequest(mId);
                    }
                    this.HandleError(argEx, null);
                }
                catch (ArgumentException argEx)
                {
                    if (mType == CoAPMessageType.CON)
                    {
                        this.RespondToBadCONRequest(mId);
                    }
                    this.HandleError(argEx, null);
                }
                catch (CoAPFormatException fEx)
                {
                    //Invalid message..
                    if (mType == CoAPMessageType.CON)
                    {
                        this.RespondToBadCONRequest(mId);
                    }
                    this.HandleError(fEx, null);
                }
            }
        }
        /// <summary>
        /// This thread continuously looks for messages on the socket
        /// Once available, it will post them for handling downstream
        /// </summary>
        protected void ProcessReceivedMessages()
        {
            byte[] buffer  = null;
            int    maxSize = AbstractNetworkUtils.GetMaxMessageSize();

            while (!this._isDone)
            {
                Thread.Sleep(1000);
                try
                {
                    if (this._clientSocket.Available >= 4 /*Min size of CoAP block*/)
                    {
                        buffer = new byte[maxSize * 2];
                        int    bytesRead = this._clientSocket.Receive(buffer);
                        byte[] udpMsg    = new byte[bytesRead];
                        Array.Copy(buffer, udpMsg, bytesRead);
                        byte mType = AbstractCoAPMessage.PeekMessageType(udpMsg);

                        if ((mType == CoAPMessageType.CON ||
                             mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg))
                        {
                            //This is a request
                            CoAPRequest coapReq = new CoAPRequest();
                            coapReq.FromByteStream(udpMsg);
                            coapReq.RemoteSender = this._remoteEP;//Setup who sent this message
                            string uriHost = ((IPEndPoint)this._remoteEP).Address.ToString();
                            UInt16 uriPort = (UInt16)((IPEndPoint)this._remoteEP).Port;

                            //setup the default values of host and port
                            //setup the default values of host and port
                            if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_HOST))
                            {
                                coapReq.Options.AddOption(CoAPHeaderOption.URI_HOST, AbstractByteUtils.StringToByteUTF8(uriHost));
                            }
                            if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_PORT))
                            {
                                coapReq.Options.AddOption(CoAPHeaderOption.URI_PORT, AbstractByteUtils.GetBytes(uriPort));
                            }

                            this.HandleRequestReceived(coapReq);
                        }
                        else
                        {
                            //This is a response
                            CoAPResponse coapResp = new CoAPResponse();
                            coapResp.FromByteStream(udpMsg);
                            coapResp.RemoteSender = this._remoteEP;//Setup who sent this message
                            //Remove the waiting confirmable message from the timeout queue
                            if (coapResp.MessageType.Value == CoAPMessageType.ACK ||
                                coapResp.MessageType.Value == CoAPMessageType.RST)
                            {
                                this._msgPendingAckQ.RemoveFromWaitQ(coapResp.ID.Value);
                            }
                            this.HandleResponseReceived(coapResp);
                        }
                    }
                }
                catch (SocketException se)
                {
                    //Close this client connection
                    this._isDone = true;
                    this.HandleError(se, null);
                }
                catch (ArgumentNullException argEx)
                {
                    this.HandleError(argEx, null);
                }
                catch (ArgumentException argEx)
                {
                    this.HandleError(argEx, null);
                }
                catch (CoAPFormatException fEx)
                {
                    //Invalid message..
                    this.HandleError(fEx, null);
                }
            }
        }
        /// <summary>
        /// Receive a message from the server. This will block if there
        /// are no messages. Please note, you must handle all errors (except timeout)
        /// and no error is raised.
        /// </summary>
        /// <param name="rxTimeoutMillis">
        /// The timeout value in milliseconds.The default value is 0, which indicates an infinite time-out period.
        /// Specifying -1 also indicates an infinite time-out period
        /// </param>
        /// <param name="timedOut">Is set to true on timeout</param>
        /// <returns>An instance of AbstractCoAPMessage on success, else null on error/timeout</returns>
        public AbstractCoAPMessage ReceiveMessage(int rxTimeoutMillis, ref bool timedOut)
        {
            byte[]       buffer   = null;
            int          maxSize  = AbstractNetworkUtils.GetMaxMessageSize();
            CoAPRequest  coapReq  = null;
            CoAPResponse coapResp = null;

            try
            {
                this._clientSocket.ReceiveTimeout = rxTimeoutMillis;
                buffer = new byte[maxSize * 2];
                int    bytesRead = this._clientSocket.Receive(buffer);
                byte[] udpMsg    = new byte[bytesRead];
                Array.Copy(buffer, udpMsg, bytesRead);
                byte mType = AbstractCoAPMessage.PeekMessageType(udpMsg);

                if ((mType == CoAPMessageType.CON ||
                     mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg))
                {
                    //This is a request
                    coapReq = new CoAPRequest();
                    coapReq.FromByteStream(udpMsg);
                    coapReq.RemoteSender = this._remoteEP;//Setup who sent this message
                    string uriHost = ((IPEndPoint)this._remoteEP).Address.ToString();
                    UInt16 uriPort = (UInt16)((IPEndPoint)this._remoteEP).Port;

                    //setup the default values of host and port
                    //setup the default values of host and port
                    if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_HOST))
                    {
                        coapReq.Options.AddOption(CoAPHeaderOption.URI_HOST, AbstractByteUtils.StringToByteUTF8(uriHost));
                    }
                    if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_PORT))
                    {
                        coapReq.Options.AddOption(CoAPHeaderOption.URI_PORT, AbstractByteUtils.GetBytes(uriPort));
                    }

                    return(coapReq);
                }
                else
                {
                    //This is a response
                    coapResp = new CoAPResponse();
                    coapResp.FromByteStream(udpMsg);
                    coapResp.RemoteSender = this._remoteEP;//Setup who sent this message

                    return(coapResp);
                }
            }
            catch (SocketException se)
            {
                if (se.ErrorCode == (int)SocketError.TimedOut)
                {
                    timedOut = true;
                }
                else
                {
                    throw se;
                }
            }
            return(null);
        }