예제 #1
0
        private void CreateNewSaeaForRecvSendOne()
        {
            Int32 tokenId;
            SocketAsyncEventArgs recvSAEAObjectForPool;
            SocketAsyncEventArgs sendSAEAObjectForPool;

            recvSAEAObjectForPool = new SocketAsyncEventArgs();
            sendSAEAObjectForPool = new SocketAsyncEventArgs();

            this.theBufferManager.SetBuffer(recvSAEAObjectForPool, sendSAEAObjectForPool);


            recvSAEAObjectForPool.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
            sendSAEAObjectForPool.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

            poolOfSendEventArgs.AssignTokenId();
            tokenId = poolOfRecvEventArgs.AssignTokenId() + 1000000;

            DataHoldingUserToken theTempRecvUserToken = new DataHoldingUserToken(recvSAEAObjectForPool,
                                                                                 recvSAEAObjectForPool.Offset,
                                                                                 sendSAEAObjectForPool.Offset,
                                                                                 this.socketListenerSettings.ReceivePrefixLength,
                                                                                 this.socketListenerSettings.SendPrefixLength,
                                                                                 tokenId);

            theTempRecvUserToken.CreateNewDataHolder();
            recvSAEAObjectForPool.UserToken = theTempRecvUserToken;
            sendSAEAObjectForPool.UserToken = theTempRecvUserToken;

            this.poolOfRecvEventArgs.Push(recvSAEAObjectForPool);
            this.poolOfSendEventArgs.Push(sendSAEAObjectForPool);
        }
예제 #2
0
        private void StartReceive(SocketAsyncEventArgs recvEventArgs)
        {
            // 이벤트 검사
            if (!ValidationCheckSocketAsyncEventArgs("StartReceive", recvEventArgs))
            {
                return;
            }

            try
            {
                DataHoldingUserToken recvToken = recvEventArgs.UserToken as DataHoldingUserToken;
                recvEventArgs.SetBuffer(recvToken.bufferOffsetReceive, this.socketListenerSettings.BufferSize);

                /// Receive 시작
                /// true  : Receive 비동기 진행중
                /// false : Receive 동기 처리됨 (Receive 됨)
                bool willRaiseEvent = recvEventArgs.AcceptSocket.ReceiveAsync(recvEventArgs);
                if (!willRaiseEvent)
                {
                    SocketListener.Log.WRN(recvEventArgs, "StartReceive in if (!willRaiseEvent).");
                    //Thread.Sleep(50);
                    //ProcessReceive(recvEventArgs);
                }
            }
            catch (Exception ex)
            {
                SocketListener.Log.ERR(recvEventArgs, string.Format("StartReceive : {0} ", ex.Message));
                SocketAsyncOperation lastOper = recvEventArgs.LastOperation;
                SocketListener.Log.ERR(recvEventArgs, string.Format("SocketAsyncOperation - {0}!!", recvEventArgs.LastOperation.ToString()));
                SocketListener.Log.ERR(recvEventArgs, string.Format("SocketFlags - {0}!!", recvEventArgs.SocketFlags.ToString()));

                //Thread.Sleep(50);
                //StartReceive(recvEventArgs);
            }
        }
예제 #3
0
        /// <summary>
        /// UDP 로 전달받은 메세지를 Client 로 알림
        /// </summary>
        /// <param name="userId">알림 받을 UserID</param>
        /// <param name="message">알림 받을 메세지</param>
        internal void SendMessageNotiftyToClient(byte[] messageBytes, string userId)
        {
            FACInfo facInfo = FACContainer.FindFACInfo(userId);

            if (facInfo == null)
            {
                return;
            }

            SocketAsyncEventArgs sendEventArgs = facInfo.sendEventArgs;

            if (sendEventArgs == null)
            {
                return;
            }

            /// 전문 By Pass

            /// 버퍼로 복사
            DataHoldingUserToken sendToken = (DataHoldingUserToken)sendEventArgs.UserToken;

            sendToken.dataToSend = new byte[messageBytes.Length];
            Buffer.BlockCopy(messageBytes, 0, sendToken.dataToSend, 0, messageBytes.Length);

            this.SendMessage(sendEventArgs);
        }
예제 #4
0
        internal void WRN(SocketAsyncEventArgs e, params string[] messages)
        {
            string strMsg      = "";
            string strRemoteIp = "";
            int    nRemotePort = 0;
            int    nToken      = 0;

            DataHoldingUserToken dToken = e.UserToken as DataHoldingUserToken;

            if (dToken != null)
            {
                strRemoteIp = dToken.RemoteIp;
                nRemotePort = dToken.RemotePort;
                nToken      = dToken.TokenId;
            }
            else
            {
                AcceptOpUserToken aToken = e.UserToken as AcceptOpUserToken;
                strRemoteIp = aToken.RemoteIp;
                nRemotePort = aToken.RemotePort;
                nToken      = aToken.TokenId;
            }
            strMsg = string.Format("{0,-15}:{1}/{2}|{3}"
                                   , strRemoteIp
                                   , nRemotePort
                                   , nToken
                                   , string.Join("\t", messages)
                                   );

            AppLog.Write(LOG_LEVEL.WRN, strMsg);
        }
예제 #5
0
        /// <summary>
        /// Accept, Login 된 client 정보 제거
        /// </summary>
        /// <param name="e">SAEA 객체</param>
        public static bool Remove(SocketAsyncEventArgs e)
        {
            lock (FACContainer.LockThis)
            {
                IPEndPoint           ep     = null;
                DataHoldingUserToken dToken = e.UserToken as DataHoldingUserToken;
                ep = dToken.IpEndPt;

                //IPEndPoint ep = e.RemoteEndPoint as IPEndPoint;
                //if (dToken != null)
                //{
                //    ep = dToken.IpEndPt;
                //}
                //else
                //{
                //    AcceptOpUserToken aToken = e.UserToken as AcceptOpUserToken;
                //    ep = aToken.IpEndPt;
                //}

                //if(e.AcceptSocket == null)
                //	return false;

                //EndPoint endPoint = e.AcceptSocket.RemoteEndPoint;

                //DataHoldingUserToken receiveSendToken = (e.UserToken as DataHoldingUserToken);
                //EndPoint endPoint = e.AcceptSocket.RemoteEndPoint;
                if (ep == null)
                {
                    return(false);
                }

                FACInfo facInfo = null;
                if (!FACContainer.Instance.FacList.TryGetValue(ep, out facInfo))
                {
                    return(false);
                }

                // 사용자맵 정보 제거
                List <EndPoint> mapEndPoint;
                if (FACContainer.Instance.FacMapList.TryGetValue(facInfo.USER_ID, out mapEndPoint))
                {
                    if (mapEndPoint.Count == 1)
                    {
                        FACContainer.Instance.FacMapList.Remove(facInfo.USER_ID);
                    }
                    else
                    {
                        FACContainer.Instance.FacMapList[facInfo.USER_ID].Remove(ep);
                    }
                }

                // FAC 정보 제거
                if (FACContainer.Instance.FacList.ContainsKey(ep))
                {
                    FACContainer.Instance.FacList.Remove(ep);
                }

                return(true);
            }
        }
예제 #6
0
        /// <summary>
        /// 로그인
        /// </summary>
        private MessageStream MessageLogin(MessageReader reader, SocketAsyncEventArgs receiveSendEventArgs)
        {
            MessageStream response       = null;
            string        user_id        = reader.GetParam(0);
            string        user_pw        = reader.GetParam(1);
            string        user_name      = "";
            string        recv_faxbox_id = "";
            string        send_faxbox_id = "";

            /// ipep.ToString() : 100.100.106.230:2038
            /// ipep.Address.ToString() : 100.100.106.230
            IPEndPoint ipep = (IPEndPoint)receiveSendEventArgs.AcceptSocket.RemoteEndPoint;

            RESULT result = DbModule.Instance.FAS_LoginAgentClient(user_id, user_pw, ipep.ToString(), ref user_name, ref recv_faxbox_id, ref send_faxbox_id);

            if (result == RESULT.F_DB_NOTEXIST_USER_ID ||
                result == RESULT.F_DB_PASSWORD_MISMATCH)
            {
                response = MessageStream.Response(MessagePacketNameEnum.LOGIN, reader.Header, false, "사용자 ID가 없거나 암호가 잘못되었습니다.");
            }
            else if (result == RESULT.SUCCESS ||
                     result == RESULT.F_DB_LOGIN_DUPLICATED)
            {
                /// /CLOSE 전문 발송 (중복 로그인)
                if (result == RESULT.F_DB_LOGIN_DUPLICATED)
                {
                    FACInfo oldFacInfo = FACContainer.FindFACInfo(user_id);
                    if (oldFacInfo != null)
                    {
                        if (this.OnLoginDuplicated != null)
                        {
                            this.OnLoginDuplicated(oldFacInfo);
                        }
                    }
                }

                DataHoldingUserToken receiveSendToken = (receiveSendEventArgs.UserToken as DataHoldingUserToken);

                /// Login 된 Client 로 추가
                FACContainer.Update(receiveSendEventArgs.AcceptSocket, user_id, user_name);

                response = MessageStream.Response(MessagePacketNameEnum.LOGIN, reader.Header, "성공");
                response.AddPrameters(reader.GetParam(0));
                response.AddPrameters(user_name);
                response.AddPrameters(recv_faxbox_id);
                response.AddPrameters(send_faxbox_id);
                response.AddPrameters(((int)Config.CLIENT_ALIVE_INTERVAL).ToString());
                response.AddPrameters(((int)Config.CLIENT_LIMIT_RESPONSE_TIME).ToString());
                response.AddPrameters(Config.HOME_PATH_HTTP);
            }
            else
            {
                response = MessageStream.Response(MessagePacketNameEnum.LOGIN, reader.Header, false, result.ToString());
            }

            return(response);
        }
예제 #7
0
        private void SendMessage(SocketAsyncEventArgs sendEventArgs)
        {
            DataHoldingUserToken sendToken = (DataHoldingUserToken)sendEventArgs.UserToken;

            sendToken.sendBytesRemainingCount = sendToken.dataToSend.Length;
            sendToken.bytesSentAlreadyCount   = 0;

            sendToken.CreateNewDataHolder();
            sendToken.Reset();

            this.StartSend(sendEventArgs);
        }
예제 #8
0
        private void StartSend(SocketAsyncEventArgs sendEventArgs)
        {
            try
            {
                // 이벤트 검사
                if (!ValidationCheckSocketAsyncEventArgs("StartSend", sendEventArgs))
                {
                    return;
                }

                int nRemainingCnt = 0;
                DataHoldingUserToken sendToken = sendEventArgs.UserToken as DataHoldingUserToken;
                nRemainingCnt = sendToken.sendBytesRemainingCount;
                if (nRemainingCnt <= 0)
                {
                    SocketListener.Log.TRC(sendEventArgs, string.Format("StartSend : Invalid DataHoldingUserToken sendBytesRemainingCount count({0}). ", sendToken.sendBytesRemainingCount));
                    return;
                }

                if (nRemainingCnt <= this.socketListenerSettings.BufferSize)
                {
                    nRemainingCnt = sendToken.sendBytesRemainingCount;
                }
                else
                {
                    nRemainingCnt = this.socketListenerSettings.BufferSize;
                }

                sendEventArgs.SetBuffer(sendToken.bufferOffsetSend, nRemainingCnt);

                Buffer.BlockCopy(sendToken.dataToSend,
                                 sendToken.bytesSentAlreadyCount,
                                 sendEventArgs.Buffer,
                                 sendToken.bufferOffsetSend,
                                 nRemainingCnt);

                // 반환 값:
                //     I/O 작업이 보류 중인 경우 true를 반환합니다.작업이 완료되면 e 매개 변수에 대한 System.Net.Sockets.SocketAsyncEventArgs.Completed
                //     이벤트가 발생합니다.I/O 작업이 동기적으로 완료된 경우 false를 반환합니다.이 경우에는 e 매개 변수에서 System.Net.Sockets.SocketAsyncEventArgs.Completed
                //     이벤트가 발생하지 않으며, 메서드 호출이 반환된 직후 매개 변수로 전달된 e 개체를 검사하여 작업 결과를 검색할 수 있습니다.
                bool willRaiseEvent = sendEventArgs.AcceptSocket.SendAsync(sendEventArgs);
                if (!willRaiseEvent)
                {
                    SocketListener.Log.WRN(sendEventArgs, "StartSend in if (!willRaiseEvent).");
                    //Thread.Sleep(50);
                    //ProcessSend(sendEventArgs);
                }
            }
            catch (Exception ex)
            {
                SocketListener.Log.ERR(sendEventArgs, string.Format("StartSend : {0}\r\n{1}. ", ex.Message, ex.StackTrace));
            }
        }
예제 #9
0
        internal Int32 HandlePrefix(SocketAsyncEventArgs e, DataHoldingUserToken receiveSendToken, Int32 remainingBytesToProcess)
        {
            lock (this)
            {
                if (receiveSendToken.receivedPrefixBytesDoneCount == 0)
                {
                    receiveSendToken.byteArrayForPrefix = new Byte[receiveSendToken.receivePrefixLength];
                }

                if (remainingBytesToProcess >= receiveSendToken.receivePrefixLength - receiveSendToken.receivedPrefixBytesDoneCount)
                {
                    //SocketListener.SocketListenerFileLog.WriteLine("PrefixHandler, enough for prefix " + receiveSendToken.TokenId + ". remainingBytesToProcess = " + remainingBytesToProcess);

                    Buffer.BlockCopy(e.Buffer,
                                     receiveSendToken.receiveMessageOffset - receiveSendToken.receivePrefixLength + receiveSendToken.receivedPrefixBytesDoneCount,
                                     receiveSendToken.byteArrayForPrefix,
                                     receiveSendToken.receivedPrefixBytesDoneCount,
                                     receiveSendToken.receivePrefixLength - receiveSendToken.receivedPrefixBytesDoneCount);

                    receiveSendToken.recPrefixBytesDoneThisOp = receiveSendToken.receivePrefixLength - receiveSendToken.receivedPrefixBytesDoneCount;

                    receiveSendToken.receivedPrefixBytesDoneCount = receiveSendToken.receivePrefixLength;

                    receiveSendToken.lengthOfCurrentIncomingMessage = int.Parse(Encoding.Default.GetString(receiveSendToken.byteArrayForPrefix, 1, receiveSendToken.receivePrefixLength - 1));
                }
                else
                {
                    //SocketListener.SocketListenerFileLog.WriteLine("PrefixHandler, NOT all of prefix " + receiveSendToken.TokenId + ". remainingBytesToProcess = " + remainingBytesToProcess);

                    Buffer.BlockCopy(e.Buffer,
                                     receiveSendToken.receiveMessageOffset - receiveSendToken.receivePrefixLength + receiveSendToken.receivedPrefixBytesDoneCount,
                                     receiveSendToken.byteArrayForPrefix,
                                     receiveSendToken.receivedPrefixBytesDoneCount,
                                     remainingBytesToProcess);

                    receiveSendToken.recPrefixBytesDoneThisOp      = remainingBytesToProcess;
                    receiveSendToken.receivedPrefixBytesDoneCount += remainingBytesToProcess;
                    remainingBytesToProcess = 0;
                }

                if (remainingBytesToProcess == 0)
                {
                    receiveSendToken.receiveMessageOffset     = receiveSendToken.receiveMessageOffset - receiveSendToken.recPrefixBytesDoneThisOp;
                    receiveSendToken.recPrefixBytesDoneThisOp = 0;
                }
            }
            return(remainingBytesToProcess);
        }
예제 #10
0
        /// <summary>
        /// SAEA 객체로 접속한 client 찾기
        /// </summary>
        /// <param name="e">Receive, Send SAEA 객체</param>
        /// <returns>FACInfo</returns>
        public static FACInfo FindFACInfo(SocketAsyncEventArgs e)
        {
            try
            {
                DataHoldingUserToken dToken = e.UserToken as DataHoldingUserToken;
                if (dToken == null)
                {
                    return(null);
                }

                EndPoint endPoint = dToken.IpEndPt;
                return(FACContainer.FindFACInfo(endPoint));
            }
            catch
            {
                return(null);
            }

            ////EndPoint endPoint = e.AcceptSocket.RemoteEndPoint;
            ////return FACContainer.FindFACInfo(endPoint);

            ////FACInfo fInfo = null;
            ////IPEndPoint ep = null;
            //try
            //{
            //    DataHoldingUserToken dToken = e.UserToken as DataHoldingUserToken;
            //    if (dToken != null)
            //    {
            //        ep = dToken.IpEndPt;
            //    }
            //    else
            //    {
            //        AcceptOpUserToken aToken = e.UserToken as AcceptOpUserToken;
            //        ep = aToken.IpEndPt;
            //    }

            //    EndPoint endPoint = ep;//e.AcceptSocket.RemoteEndPoint;
            //    fInfo = FACContainer.FindFACInfo(endPoint);
            //}
            //catch
            //{
            //    fInfo = null;
            //}

            //return fInfo;
        }
예제 #11
0
        /// <summary>
        /// Client 로 전문 보내기
        /// </summary>
        /// <param name="sendEventArgs">보낼 SAEA 객체</param>
        /// <param name="packetName">옵션 : 특정전문 지정</param>
        /// <param name="userId">옵션 : 사용자 ID</param>
        /// <param name="message">옵션 : 메세지</param>
        internal void SendMessageToClient(SocketAsyncEventArgs sendEventArgs, MessagePacketNameEnum packetName = MessagePacketNameEnum.EMPTY, string userId = "")
        {
            DataHoldingUserToken sendToken = (DataHoldingUserToken)sendEventArgs.UserToken;
            MessageStream        response  = null;

            /// 전문 생성
            response = messageParsing.GetResponse(sendEventArgs, packetName, userId);
            if (response == null)
            {
                return;
            }

            /// 버퍼로 복사
            int readByteAll = response.ReadAll(ref sendToken.dataToSend, this.socketListenerSettings.BufferSize);

            this.SendMessage(sendEventArgs);
        }
예제 #12
0
        /// <summary>
        /// 전문 헤더 생성
        /// </summary>
        /// <param name="sendEventArgs">보낼 SAEA 객체</param>
        /// <returns>MessageReader</returns>
        public MessageReader GetResponseHeader(SocketAsyncEventArgs sendEventArgs)
        {
            MessageReader        reader           = null;
            DataHoldingUserToken receiveSendToken = (sendEventArgs.UserToken as DataHoldingUserToken);

            /// STX, ETX 제거
            int bufferLength = receiveSendToken.dataToReceive.Length - 2;

            byte[] buffer = new byte[bufferLength];
            Buffer.BlockCopy(receiveSendToken.dataToReceive, 1, buffer, 0, bufferLength);

            /// 전문 헤더 검사
            try
            {
                reader = new MessageReader(buffer);
            }
            catch (Exception ex)
            {
                SocketListener.Log.ExceptionLog(ex, "전문 헤더 오류");
            }
            return(reader);
        }
예제 #13
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            // 이벤트 검사
            if (!ValidationCheckSocketAsyncEventArgs("ProcessAccept", acceptEventArgs))
            {
                this.StartAccept();
                this.HandleBadAccept(acceptEventArgs);
                return;
            }

            // 최대 접속자 수 설정
            Int32 max = this.maxSimultaneousClientsThatWereConnected;
            Int32 numberOfConnectedSockets = Interlocked.Increment(ref this.numberOfAcceptedSockets);

            if (numberOfConnectedSockets > max)
            {
                Interlocked.Increment(ref this.maxSimultaneousClientsThatWereConnected);
            }

            // 다음 소켓 이벤트 대기 처리 : acceptEventArgs -> recvEventArgs, sendEventArgs
            StartAccept();

            SocketListener.Log.MSG(acceptEventArgs, string.Format("Start accept processing !! poolOfAcceptEventArgs:{0}, poolOfRecvEventArgs:{1}, poolOfSendEventArgs:{2}"
                                                                  , this.poolOfAcceptEventArgs.Count
                                                                  , this.poolOfRecvEventArgs.Count
                                                                  , this.poolOfSendEventArgs.Count));

            try
            {
                // Accept 된 Client 로 추가 : acceptEventArgs -> recvEventArgs, sendEventArgs
                if (this.poolOfRecvEventArgs.Count <= 1 || this.poolOfSendEventArgs.Count <= 1)
                {
                    this.CreateNewSaeaForRecvSendOne();
                }

                AcceptOpUserToken    aToken        = acceptEventArgs.UserToken as AcceptOpUserToken;
                SocketAsyncEventArgs recvEventArgs = null;
                SocketAsyncEventArgs sendEventArgs = null;

                while (true)
                {
                    recvEventArgs = this.poolOfRecvEventArgs.Pop();
                    sendEventArgs = this.poolOfSendEventArgs.Pop();

                    if (recvEventArgs.Buffer == null || sendEventArgs.Buffer == null)
                    {
                        DataHoldingUserToken dToken = recvEventArgs.UserToken as DataHoldingUserToken;
                        if (dToken != null)
                        {
                            this.theBufferManager.SetBuffer(dToken.BufferOffsetRecv, recvEventArgs);
                            SocketListener.Log.WRN(string.Format("Receive SocketAsyncEventArgs buffer is null. reset buffer. Reuse later!! token:{0}, token_offset:{1}, recv_offset:{2}", dToken.TokenId, dToken.BufferOffsetRecv, recvEventArgs.Offset));
                        }

                        dToken = sendEventArgs.UserToken as DataHoldingUserToken;
                        if (dToken != null)
                        {
                            this.theBufferManager.SetBuffer(dToken.BufferOffsetSend, sendEventArgs);
                            SocketListener.Log.WRN(string.Format("Send SocketAsyncEventArgs buffer is null. reset buffer. Reuse later!! token:{0}, token_offset:{1}, send_offset:{2}", dToken.TokenId, dToken.BufferOffsetSend, sendEventArgs.Offset));
                        }

                        this.poolOfRecvEventArgs.Push(recvEventArgs);
                        this.poolOfSendEventArgs.Push(sendEventArgs);
                        continue;
                    }

                    break;
                }

                InitSocketAsyncEventArgs(ref recvEventArgs);
                InitSocketAsyncEventArgs(ref sendEventArgs);

                SocketListener.Log.MSG(string.Format("Start accept processing !! SocketAsyncEventArgs buffer offset. recv_offset:{0}, send_offset:{1}", recvEventArgs.Offset, sendEventArgs.Offset));

                (recvEventArgs.UserToken as DataHoldingUserToken).CreateSessionId();
                (recvEventArgs.UserToken as DataHoldingUserToken).RemoteIp   = aToken.RemoteIp;
                (recvEventArgs.UserToken as DataHoldingUserToken).RemotePort = aToken.RemotePort;
                (recvEventArgs.UserToken as DataHoldingUserToken).IpEndPt    = aToken.IpEndPt;

                (sendEventArgs.UserToken as DataHoldingUserToken).CreateSessionId();
                (sendEventArgs.UserToken as DataHoldingUserToken).RemoteIp   = aToken.RemoteIp;
                (sendEventArgs.UserToken as DataHoldingUserToken).RemotePort = aToken.RemotePort;
                (sendEventArgs.UserToken as DataHoldingUserToken).IpEndPt    = aToken.IpEndPt;


                recvEventArgs.AcceptSocket = acceptEventArgs.AcceptSocket;
                //recvEventArgs.SocketError = acceptEventArgs.SocketError;

                sendEventArgs.AcceptSocket = acceptEventArgs.AcceptSocket;
                //sendEventArgs.SocketError = sendEventArgs.SocketError;

                (recvEventArgs.UserToken as DataHoldingUserToken).socketHandleNumber = (Int32)recvEventArgs.AcceptSocket.Handle;
                (sendEventArgs.UserToken as DataHoldingUserToken).socketHandleNumber = (Int32)sendEventArgs.AcceptSocket.Handle;

                // 이벤트 반납
                aToken.RemoteIp              = "";
                aToken.RemotePort            = 0;
                aToken.IpEndPt               = null;
                acceptEventArgs.AcceptSocket = null;
                this.poolOfAcceptEventArgs.Push(acceptEventArgs);

                string strMsg;
                FACContainer.AddEx(recvEventArgs.AcceptSocket, recvEventArgs, sendEventArgs, out strMsg);
                if (!string.IsNullOrEmpty(strMsg))
                {
                    SocketListener.Log.WRN(recvEventArgs, string.Format("FACContainer AddEx - {0}!!", strMsg));
                }

                this.DisplayConnectionInfo();

                /// Accept 알림 보내기
                SendMessageToClient(sendEventArgs, MessagePacketNameEnum.ACCPT);

                /// 수신 대기
                StartReceive(recvEventArgs);
            }
            catch (Exception ex)
            {
                // REMOVE - KIMCG : 20140827
                // Exception 발생시 재귀 호출로인해 Accept pool 에서 이벤트가 빠진다. -> 추후 이벤트 부족으로 작업불가함.
                // StartAccept();
                // HandleBadAccept(acceptEventArgs);
                // REMOVE - END
                SocketListener.Log.ERR(string.Format("ProcessAccept - message:{0}\r\nstac_trace:{1}\r\nsource:{2}", ex.Message, ex.StackTrace, ex.Source));
            }
        }
예제 #14
0
        internal bool HandleMessage(SocketAsyncEventArgs receiveSendEventArgs, DataHoldingUserToken receiveSendToken, Int32 remainingBytesToProcess)
        {
            bool incomingTcpMessageIsReady = false;

            lock (this)
            {
                if (receiveSendToken.receivedMessageBytesDoneCount == 0)
                {
                    //SocketListener.Log.Write("MessageHandler, creating receive array " + receiveSendToken.TokenId);

                    receiveSendToken.dataToReceive = new Byte[receiveSendToken.lengthOfCurrentIncomingMessage];
                }

                if (remainingBytesToProcess + receiveSendToken.receivedMessageBytesDoneCount == receiveSendToken.lengthOfCurrentIncomingMessage)
                {
                    //SocketListener.Log.Write("MessageHandler, length is right for " + receiveSendToken.TokenId);

                    Buffer.BlockCopy(receiveSendEventArgs.Buffer,
                                     receiveSendToken.receiveMessageOffset - receiveSendToken.receivePrefixLength,
                                     receiveSendToken.dataToReceive,
                                     receiveSendToken.receivedMessageBytesDoneCount,
                                     remainingBytesToProcess);

                    incomingTcpMessageIsReady = true;
                }
                else
                {
                    try
                    {
                        Buffer.BlockCopy(receiveSendEventArgs.Buffer,
                                         receiveSendToken.receiveMessageOffset,
                                         receiveSendToken.dataToReceive,
                                         receiveSendToken.receivedMessageBytesDoneCount,
                                         remainingBytesToProcess);
                    }
                    catch (Exception ex)
                    {
                        SocketListener.Log.WRN("MessageHandler, length is short for " + receiveSendToken.TokenId);
                        SocketListener.Log.WRN(string.Format("receiveMessageOffset:{0}, receivedMessageBytesDoneCount:{1}, remainingBytesToProcess:{2}"
                                                             , receiveSendToken.receiveMessageOffset
                                                             , receiveSendToken.receivedMessageBytesDoneCount
                                                             , remainingBytesToProcess));
                        SocketListener.Log.WRN(ex.Message);
                    }

                    receiveSendToken.receiveMessageOffset           = receiveSendToken.receiveMessageOffset - receiveSendToken.recPrefixBytesDoneThisOp;
                    receiveSendToken.receivedMessageBytesDoneCount += remainingBytesToProcess;
                }

                //else if (remainingBytesToProcess + receiveSendToken.receivedMessageBytesDoneCount < receiveSendToken.lengthOfCurrentIncomingMessage)
                //{
                //    SocketListener.Log.Write("MessageHandler, length is short for " + receiveSendToken.TokenId);

                //    try
                //    {
                //        Buffer.BlockCopy(receiveSendEventArgs.Buffer,
                //                         receiveSendToken.receiveMessageOffset,
                //                         receiveSendToken.dataToReceive,
                //                         receiveSendToken.receivedMessageBytesDoneCount,
                //                         remainingBytesToProcess);

                //    }
                //    catch (Exception ex)
                //    {
                //        SocketListener.Log.Write("MessageHandler, length is short for " + receiveSendToken.TokenId +
                //            ", " + ex.ToString());
                //    }

                //    receiveSendToken.receiveMessageOffset = receiveSendToken.receiveMessageOffset - receiveSendToken.recPrefixBytesDoneThisOp;
                //    receiveSendToken.receivedMessageBytesDoneCount += remainingBytesToProcess;

                //    incomingTcpMessageIsReady = true;
                //}
                //else
                //{
                //    SocketListener.Log.Write("MessageHandler, length is large for " + receiveSendToken.TokenId);

                //    try
                //    {
                //        Buffer.BlockCopy(receiveSendEventArgs.Buffer,
                //                        receiveSendToken.receiveMessageOffset - receiveSendToken.receivePrefixLength,
                //                        receiveSendToken.dataToReceive,
                //                        receiveSendToken.receivedMessageBytesDoneCount,
                //                        receiveSendToken.lengthOfCurrentIncomingMessage);
                //    }
                //    catch (Exception ex)
                //    {
                //        SocketListener.Log.Write("MessageHandler, length is large for " + receiveSendToken.TokenId +
                //            ", " + ex.ToString());
                //    }

                //    incomingTcpMessageIsReady = true;
                //}
            }

            return(incomingTcpMessageIsReady);
        }
예제 #15
0
        private bool ValidationCheckSocketAsyncEventArgs(string strFuncName, SocketAsyncEventArgs e)
        {
            string strRemoteIp = "";
            int    nRemotePort = 0;
            int    nToken      = 0;

            DataHoldingUserToken dToken = e.UserToken as DataHoldingUserToken;

            if (dToken != null)
            {
                strRemoteIp = dToken.RemoteIp;
                nRemotePort = dToken.RemotePort;
                nToken      = dToken.TokenId;
            }
            else
            {
                AcceptOpUserToken aToken = e.UserToken as AcceptOpUserToken;
                strRemoteIp = aToken.RemoteIp;
                nRemotePort = aToken.RemotePort;
                nToken      = aToken.TokenId;
            }

            if (e.AcceptSocket == null)
            {
                SocketListener.Log.ERR(string.Format("{0,-15}:{1}/{2}|{3} - AcceptSocket is null."
                                                     , strRemoteIp
                                                     , nRemotePort
                                                     , nToken
                                                     , strFuncName
                                                     ));
                return(false);
            }

            //IPEndPoint remoteIpEndPoint = e.AcceptSocket.RemoteEndPoint as IPEndPoint;
            //if (remoteIpEndPoint == null)
            //{
            //    SocketListener.Log.ERR(string.Format("{0,-15}:{1}/{2}|{3} - RemoteIpEndPoint is null."
            //                            , strRemoteIp
            //                            , nRemotePort
            //                            , nToken
            //                            , strFuncName
            //                            ));
            //    return false;
            //}

            SocketError sockErr = e.SocketError;

            if (sockErr != SocketError.Success)
            {
                SocketListener.Log.ERR(string.Format("{0,-15}:{1}/{2}|{3} - Socket error : {4}."
                                                     , strRemoteIp
                                                     , nRemotePort
                                                     , nToken
                                                     , strFuncName
                                                     , sockErr
                                                     ));

                return(false);
            }

            return(true);
        }
예제 #16
0
        /// <summary>
        /// Shutdown -> Close
        /// </summary>
        private bool CloseClientSocket(SocketAsyncEventArgs e)
        {
            try
            {
                SocketListener.Log.MSG(e, "Start Close FaxAgent.");
                DataHoldingUserToken receiveSendToken = e.UserToken as DataHoldingUserToken;
                if (receiveSendToken.dataToReceive != null)
                {
                    receiveSendToken.CreateNewDataHolder();
                }

                // 로그아웃 처리
                FACInfo facInfo = FACContainer.FindFACInfo(e);
                if (facInfo != null)
                {
                    // DB Logout 처리
                    if (FACContainer.LoginedList.Count > 0 && facInfo.USER_ID != "")
                    {
                        if (DbModule.Instance.FAS_LogoutAgentClient(facInfo.USER_ID) != Btfax.CommonLib.RESULT.SUCCESS)
                        {
                            SocketListener.Log.WRN(e, "Database Logout process failure");
                        }
                        else
                        {
                            SocketListener.Log.MSG(e, "Database Logout process success");
                        }
                    }
                }

                // socket close
                try     { e.AcceptSocket.Shutdown(SocketShutdown.Both); }
                catch { }

                if (e.AcceptSocket != null)
                {
                    try {
                        e.AcceptSocket.Close();
                        e.AcceptSocket = null;
                    }
                    catch { };
                }

                if (facInfo != null)
                {
                    this.poolOfRecvEventArgs.Push(facInfo.recvEventArgs);
                    this.poolOfSendEventArgs.Push(facInfo.sendEventArgs);
                }
                else
                {
                    this.CreateNewSaeaForRecvSendOne();
                    SocketListener.Log.MSG(string.Format("CreateNewSaeaForRecvSendOne this.poolOfRecvEventArgs:{0}, this.poolOfSendEventArgs.Push{1}"
                                                         , this.poolOfRecvEventArgs.Count
                                                         , this.poolOfSendEventArgs.Count));
                }

                FACContainer.Remove(e);

                // Accept count 감소
                Interlocked.Decrement(ref this.numberOfAcceptedSockets);
                this.theMaxConnectionsEnforcer.Release();

                SocketListener.Log.MSG(e, string.Format("Close FaxAgent success."));
                this.DisplayConnectionInfo();
                return(true);
            }
            catch (Exception ex)
            {
                // Accept count 감소
                Interlocked.Decrement(ref this.numberOfAcceptedSockets);
                this.theMaxConnectionsEnforcer.Release();

                SocketListener.Log.ERR(string.Format("CloseClientSocket : {0}\r\n{1}", ex.Message, ex.StackTrace));
                return(false);
            }
        }
예제 #17
0
        private void ProcessSend(SocketAsyncEventArgs sendEventArgs)
        {
            int nRemainingCnt = 0;

            // 이벤트 검사
            if (!ValidationCheckSocketAsyncEventArgs("ProcessSend", sendEventArgs))
            {
                return;
            }

            DataHoldingUserToken sendToken = sendEventArgs.UserToken as DataHoldingUserToken;

            nRemainingCnt = sendToken.sendBytesRemainingCount;
            if (nRemainingCnt <= 0)
            {
                SocketListener.Log.TRC(sendEventArgs, string.Format("ProcessSend : Invalid DataHoldingUserToken sendBytesRemainingCount count({0}).", sendToken.sendBytesRemainingCount));
                return;
            }

            FACInfo facInfo = FACContainer.FindFACInfo(sendEventArgs);

            if (facInfo == null)
            {
                SocketListener.Log.WRN(sendEventArgs, "ProcessSend : Not found FaxAgentInfo.");
                return;
            }

            facInfo.LastResponseTime = DateTime.Now;

            LOG_LEVEL logLv      = LOG_LEVEL.MSG;
            string    packetName = m_Encoding.GetString(sendToken.dataToSend, 34, 5);

            if (packetName == MessagePacketNameEnum.ALIVE.ToString())
            {
                logLv = LOG_LEVEL.TRC;
            }
            else
            {
                logLv = LOG_LEVEL.MSG;
            }

            // 패킷 로그
            SocketListener.Log.LogWrite(logLv,
                                        "SEND    ",
                                        sendEventArgs.AcceptSocket.RemoteEndPoint.ToString(),
                                        sendEventArgs.AcceptSocket.Handle.ToInt32(),
                                        sendToken.TokenId,
                                        sendToken.dataToSend.Length,
                                        m_Encoding.GetString(sendToken.dataToSend));

            sendToken.sendBytesRemainingCount = sendToken.sendBytesRemainingCount - sendEventArgs.BytesTransferred;

            sendToken.bytesSentAlreadyCount += sendEventArgs.BytesTransferred;

            // send async
            StartSend(sendEventArgs);

            if (packetName == MessagePacketNameEnum.LOGIN.ToString())
            {
                this.DisplayConnectionInfo();
            }
        }
예제 #18
0
        private void ProcessReceive(SocketAsyncEventArgs recvEventArgs)
        {
            DataHoldingUserToken recvToken = recvEventArgs.UserToken as DataHoldingUserToken;

            // 이벤트 검사
            if (!ValidationCheckSocketAsyncEventArgs("ProcessReceive", recvEventArgs))
            {
                recvToken.Reset();
                this.CloseClientSocket(recvEventArgs);
                return;
            }

            try
            {
                if (recvEventArgs.BytesTransferred == 0)
                {
                    SocketListener.Log.WRN(recvEventArgs, "RecvEventArgs.BytesTransferred is zero. !!");
                    recvToken.Reset();
                    this.CloseClientSocket(recvEventArgs);
                    return;
                }

                FACInfo facInfo = FACContainer.FindFACInfo(recvEventArgs);
                if (facInfo == null)
                {
                    SocketListener.Log.ERR(recvEventArgs, "Not found facinfo.");
                    recvToken.Reset();
                    return;
                }

                facInfo.LastRequestTime = DateTime.Now;

                Int32 remainingBytesToProcess = recvEventArgs.BytesTransferred;

                if (recvToken.receivedPrefixBytesDoneCount < this.socketListenerSettings.ReceivePrefixLength)
                {
                    /// 공통 전문 첫 컬럼 (전문길이) 읽기
                    remainingBytesToProcess = prefixHandler.HandlePrefix(recvEventArgs, recvToken, remainingBytesToProcess);
                    if (remainingBytesToProcess == 0)
                    {
                        SocketListener.Log.WRN(recvEventArgs, "RemainingBytesToProcess is zero. !!");
                        StartReceive(recvEventArgs);
                        return;
                    }
                }

                // 전문길이만큼 전문 읽기
                bool incomingTcpMessageIsReady = messageHandler.HandleMessage(recvEventArgs, recvToken, remainingBytesToProcess);
                if (incomingTcpMessageIsReady == true)
                {
                    SocketAsyncEventArgs sendEventArgs = facInfo.sendEventArgs;
                    if (recvEventArgs == null)
                    {
                        recvToken.Reset();
                        //CloseClientSocket(recvEventArgs);
                        return;
                    }

                    LOG_LEVEL logLv      = LOG_LEVEL.MSG;
                    string    packetName = m_Encoding.GetString(recvToken.dataToReceive, 34, 5);
                    if (packetName == MessagePacketNameEnum.ALIVE.ToString())
                    {
                        logLv = LOG_LEVEL.TRC;
                    }
                    else
                    {
                        logLv = LOG_LEVEL.MSG;
                    }

                    // 패킷 로그
                    SocketListener.Log.LogWrite(logLv,
                                                "RECEIVE ",
                                                recvEventArgs.AcceptSocket.RemoteEndPoint.ToString(),
                                                recvEventArgs.AcceptSocket.Handle.ToInt32(),
                                                recvToken.TokenId,
                                                recvToken.dataToReceive.Length,
                                                m_Encoding.GetString(recvToken.dataToReceive));

                    // 응답 전문 보내기
                    this.SendMessageToClient(sendEventArgs);
                }
                else
                {
                    recvToken.receiveMessageOffset     = recvToken.bufferOffsetReceive;
                    recvToken.recPrefixBytesDoneThisOp = 0;
                }

                StartReceive(recvEventArgs);
            }
            catch (Exception ex)
            {
                SocketListener.Log.ERR(recvEventArgs, string.Format("ProcessReceive : {0}", ex.Message));
                recvToken.Reset();
            }
        }