Fixed Stack, last-in-first-out. Fix me: this isn't Stack, this is Queue.
Beispiel #1
0
        public _SocketState(Stream strm,long maxLength,string terminator,string removeFromEnd,object tag,SocketCallBack callBack)
        {
            m_pStream    = strm;
            m_MaxLength  = maxLength;
            m_RemFromEnd = removeFromEnd;
            m_Tag        = tag;
            m_pCallback  = callBack;

            m_pStack = new _FixedStack(terminator);
            m_RecvType = ReadType.Terminator;
        }
Beispiel #2
0
        public _SocketState(Stream strm, long maxLength, string terminator, string removeFromEnd, object tag, SocketCallBack callBack)
        {
            m_pStream    = strm;
            m_MaxLength  = maxLength;
            m_RemFromEnd = removeFromEnd;
            m_Tag        = tag;
            m_pCallback  = callBack;

            m_pStack   = new _FixedStack(terminator);
            m_RecvType = ReadType.Terminator;
        }
        /// <summary>
        /// Reads reply from socket.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="replyData">Data that has been readen from socket.</param>
        /// <param name="addData">Data that has will be written at the beginning of read data. This param may be null.</param>
        /// <param name="maxLength">Maximum Length of data which may read.</param>
        /// <param name="cmdIdleTimeOut">Command idle time out in milliseconds.</param>
        /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param>
        /// <param name="removeFromEnd">Removes following string from reply.NOTE: removes only if ReadReplyCode is Ok.</param>		
        /// <returns>Return reply code.</returns>
        public static ReadReplyCode ReadData(Socket socket,out MemoryStream replyData,byte[] addData,int maxLength,int cmdIdleTimeOut,string terminator,string removeFromEnd)
        {
            ReadReplyCode replyCode = ReadReplyCode.Ok;
            replyData = null;

            try
            {
                replyData = new MemoryStream();
                _FixedStack stack = new _FixedStack(terminator);
                int nextReadWriteLen = 1;

                long lastDataTime = DateTime.Now.Ticks;
                while(nextReadWriteLen > 0){
                    if(socket.Available >= nextReadWriteLen){
                        //Read byte(s)
                        byte[] b = new byte[nextReadWriteLen];
                        int countRecieved = socket.Receive(b);

                        // Write byte(s) to buffer, if length isn't exceeded.
                        if(replyCode != ReadReplyCode.LengthExceeded){
                            replyData.Write(b,0,countRecieved);
                        }

                        // Write to stack(terminator checker)
                        nextReadWriteLen = stack.Push(b,countRecieved);

                        //---- Check if maximum length is exceeded ---------------------------------//
                        if(replyCode != ReadReplyCode.LengthExceeded && replyData.Length > maxLength){
                            replyCode = ReadReplyCode.LengthExceeded;
                        }
                        //--------------------------------------------------------------------------//

                        // reset last data time
                        lastDataTime = DateTime.Now.Ticks;
                    }
                    else{
                        //---- Idle and time out stuff ----------------------------------------//
                        if(DateTime.Now.Ticks > lastDataTime + ((long)(cmdIdleTimeOut)) * 10000){
                            replyCode = ReadReplyCode.TimeOut;
                            break;
                        }
                        System.Threading.Thread.Sleep(50);
                        //---------------------------------------------------------------------//
                    }
                }

                // If reply is ok then remove chars if any specified by 'removeFromEnd'.
                if(replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0){
                    replyData.SetLength(replyData.Length - removeFromEnd.Length);
                }
            }
            catch{
                replyCode = ReadReplyCode.UnKnownError;
            }

            return replyCode;
        }
Beispiel #4
0
        private static void ProccessData_Term(Hashtable param)
        {
            BufferedSocket socket           = (BufferedSocket)param["socket"];
            MemoryStream   strm             = (MemoryStream)param["strm"];
            string         removeFromEnd    = (string)param["removeFromEnd"];
            _FixedStack    stack            = (_FixedStack)param["stack"];
            int            nextReadWriteLen = (int)param["nextReadWriteLen"];
            object         tag      = param["tag"];
            SocketCallBack callBack = (SocketCallBack)param["callBack"];

            while (nextReadWriteLen > 0)
            {
                // We used buffer, request more data
                if (socket.AvailableInBuffer < nextReadWriteLen)
                {
                    // Store nextReadWriteLen for next call of this command
                    param["nextReadWriteLen"] = nextReadWriteLen;

                    // Recieve next bytes
                    byte[] buff = new byte[1024];
                    param["recieveBuffer"] = buff;
                    socket.BeginReceive(buff, 0, buff.Length, 0, new AsyncCallback(OnRecievedData), param);

                    // End this method, if data arrives, this method is called again
                    return;
                }

                //Read byte(s)
                byte[] b             = new byte[nextReadWriteLen];
                int    countRecieved = socket.ReceiveFromFuffer(b);

                // Increase readed count
                param["readedCount"] = ((long)param["readedCount"] + countRecieved);

                // Write byte(s) to buffer, if length isn't exceeded.
                if ((long)param["readedCount"] < (long)param["maxLength"])
                {
                    strm.Write(b, 0, countRecieved);
                }
                // Message size exceeded, we must junk stream data.
                else if (strm.Length > 0)
                {
                    strm.SetLength(0);
                }

                // Write to stack(terminator checker)
                nextReadWriteLen = stack.Push(b, countRecieved);
            }


            // If we reach so far, then we have successfully readed data

            if ((long)param["readedCount"] < (long)param["maxLength"])
            {
                // Remove "removeFromEnd" from end
                if (removeFromEnd.Length > 0 && strm.Length > removeFromEnd.Length)
                {
                    strm.SetLength(strm.Length - removeFromEnd.Length);
                }
                strm.Position = 0;

                // We got all data successfully, call EndRecieve call back
                callBack(SocketCallBackResult.Ok, (long)param["readedCount"], null, tag);
            }
            else
            {
                callBack(SocketCallBackResult.LengthExceeded, (long)param["readedCount"], null, tag);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Reads reply from socket.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="replyData">Data that has been readen from socket.</param>
        /// <param name="addData">Data that has will be written at the beginning of read data. This param may be null.</param>
        /// <param name="maxLength">Maximum Length of data which may read.</param>
        /// <param name="cmdIdleTimeOut">Command idle time out in milliseconds.</param>
        /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param>
        /// <param name="removeFromEnd">Removes following string from reply.NOTE: removes only if ReadReplyCode is Ok.</param>		
        /// <returns>Return reply code.</returns>
        public static ReadReplyCode ReadData(Socket socket,out MemoryStream replyData,byte[] addData,int maxLength,int cmdIdleTimeOut,string terminator,string removeFromEnd)
        {
            ReadReplyCode replyCode = ReadReplyCode.Ok;
            replyData = null;

            try{
                socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,cmdIdleTimeOut);

                replyData = new MemoryStream();
                _FixedStack stack = new _FixedStack(terminator);
                int nextReadWriteLen = 1;

                while(nextReadWriteLen > 0){
                    //Read byte(s)
                    byte[] b = new byte[nextReadWriteLen];
                    int countRecieved = socket.Receive(b);
                    if(countRecieved > 0){
                        // Write byte(s) to buffer, if length isn't exceeded.
                        if(replyCode != ReadReplyCode.LengthExceeded){
                            replyData.Write(b,0,countRecieved);
                        }

                        // Write to stack(terminator checker)
                        nextReadWriteLen = stack.Push(b,countRecieved);

                        //---- Check if maximum length is exceeded ---------------------------------//
                        if(replyCode != ReadReplyCode.LengthExceeded && replyData.Length > maxLength){
                            replyCode = ReadReplyCode.LengthExceeded;
                        }
                        //--------------------------------------------------------------------------//
                    }
                    // Client disconnected
                    else{
                        throw new Exception("Client disconnected");
                    }
                }

                // If reply is ok then remove chars if any specified by 'removeFromEnd'.
                if(replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0){
                    replyData.SetLength(replyData.Length - removeFromEnd.Length);
                }
            }
            catch(Exception x){
                replyCode = ReadReplyCode.UnKnownError;

                if(x is SocketException){
                    SocketException xS = (SocketException)x;
                    if(xS.ErrorCode == 10060){
                        replyCode = ReadReplyCode.TimeOut;
                    }
                }
            }

            return replyCode;
        }
Beispiel #6
0
        /// <summary>
        /// Reads reply from socket.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="replyData">Data that has been readen from socket.</param>
        /// <param name="addData">Data that has will be written at the beginning of read data. This param may be null.</param>
        /// <param name="maxLength">Maximum Length of data which may read.</param>
        /// <param name="cmdIdleTimeOut">Command idle time out in milliseconds.</param>
        /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param>
        /// <param name="removeFromEnd">Removes following string from reply.NOTE: removes only if ReadReplyCode is Ok.</param>
        /// <returns>Return reply code.</returns>
        public static ReadReplyCode ReadData(Socket socket, out MemoryStream replyData, byte[] addData, int maxLength, int cmdIdleTimeOut, string terminator, string removeFromEnd)
        {
            ReadReplyCode replyCode = ReadReplyCode.Ok;

            replyData = null;

            try{
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, cmdIdleTimeOut);

                replyData = new MemoryStream();
                _FixedStack stack            = new _FixedStack(terminator);
                int         nextReadWriteLen = 1;

                while (nextReadWriteLen > 0)
                {
                    //Read byte(s)
                    byte[] b             = new byte[nextReadWriteLen];
                    int    countRecieved = socket.Receive(b);
                    if (countRecieved > 0)
                    {
                        // Write byte(s) to buffer, if length isn't exceeded.
                        if (replyCode != ReadReplyCode.LengthExceeded)
                        {
                            replyData.Write(b, 0, countRecieved);
                        }

                        // Write to stack(terminator checker)
                        nextReadWriteLen = stack.Push(b, countRecieved);

                        //---- Check if maximum length is exceeded ---------------------------------//
                        if (replyCode != ReadReplyCode.LengthExceeded && replyData.Length > maxLength)
                        {
                            replyCode = ReadReplyCode.LengthExceeded;
                        }
                        //--------------------------------------------------------------------------//
                    }
                    // Client disconnected
                    else
                    {
                        throw new Exception("Client disconnected");
                    }
                }

                // If reply is ok then remove chars if any specified by 'removeFromEnd'.
                if (replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0)
                {
                    replyData.SetLength(replyData.Length - removeFromEnd.Length);
                }
            }
            catch (Exception x) {
                replyCode = ReadReplyCode.UnKnownError;

                if (x is SocketException)
                {
                    SocketException xS = (SocketException)x;
                    if (xS.ErrorCode == 10060)
                    {
                        replyCode = ReadReplyCode.TimeOut;
                    }
                }
            }

            return(replyCode);
        }
Beispiel #7
0
        // 3 types of read
        //   1) To some terminator
        //   2) Specified length
        //   3) While socket is closed with ShutDown

        #region method ReadData (terminator)

        /// <summary>
        /// Reads data from socket while specified terminator is reached.
        /// If maximum length is exceeded, reading continues but data won't be stored to stream.
        /// </summary>
        /// <param name="storeStream">Stream where to store readed data.</param>
        /// <param name="maxLength">Maximum length to read.</param>
        /// <param name="terminator">Terminator which trminates reading.</param>
        /// <param name="removeFromEnd">Part of trminator what to remove from end. Can be empty or max part is terminator.</param>
        /// <returns></returns>
        public ReadReplyCode ReadData(Stream storeStream, long maxLength, string terminator, string removeFromEnd)
        {
            if (storeStream == null)
            {
                throw new Exception("Parameter storeStream can't be null !");
            }

            ReadReplyCode replyCode = ReadReplyCode.Ok;

            try{
                _FixedStack stack            = new _FixedStack(terminator);
                long        readedCount      = 0;
                int         nextReadWriteLen = 1;
                while (nextReadWriteLen > 0)
                {
                    //Read byte(s)
                    byte[] b             = new byte[nextReadWriteLen];
                    int    countRecieved = this.Receive(b);
                    if (countRecieved > 0)
                    {
                        readedCount += countRecieved;

                        // Write byte(s) to buffer, if length isn't exceeded.
                        if (readedCount <= maxLength)
                        {
                            storeStream.Write(b, 0, countRecieved);
                        }

                        // Write to stack(terminator checker)
                        nextReadWriteLen = stack.Push(b, countRecieved);
                    }
                    // Client disconnected
                    else
                    {
                        return(ReadReplyCode.SocketClosed);
                    }

                    OnActivity();
                }

                // Check if length is exceeded
                if (readedCount > maxLength)
                {
                    return(ReadReplyCode.LengthExceeded);
                }

                // If reply is ok then remove chars if any specified by 'removeFromEnd'.
                if (replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0)
                {
                    storeStream.SetLength(storeStream.Length - removeFromEnd.Length);
                }

                // Logging stuff
                if (m_pLogger != null)
                {
                    if (storeStream is MemoryStream && storeStream.Length < 200)
                    {
                        MemoryStream ms = (MemoryStream)storeStream;
                        m_pLogger.AddReadEntry(m_pEncoding.GetString(ms.ToArray()));
                    }
                    else
                    {
                        m_pLogger.AddReadEntry("Big binary, readed " + readedCount.ToString() + " bytes.");
                    }
                }
            }
            catch (Exception x) {
                replyCode = ReadReplyCode.UnKnownError;

                if (x is SocketException)
                {
                    SocketException xS = (SocketException)x;
                    if (xS.ErrorCode == 10060)
                    {
                        return(ReadReplyCode.TimeOut);
                    }
                }
            }

            return(replyCode);
        }