Example #1
0
 public void StopMe()
 {
     try
     {
         if (!_isStop)
         {
             if (this.TcpIsCanUse())//发送一条对服务器的通告
             {
                 uint           seq = Tools.GetSequence_Id();
                 CMPP_Terminate t   = new CMPP_Terminate();
                 this.Send(t.Encode());
                 this.HeartStop();
                 SMSLog.Log("=SocketClient==》StopMe()==HeartStop==");
             }
             MyTools.WaitTime(10);  //等待1000ms,告知服务器
             _isStop = true;
             if (_socket != null)
             {
                 _socket.Shutdown(SocketShutdown.Both);
                 _socket.Close();
                 _socket = null;
             }
             SMSLog.Log("=SocketClient==》StopMe()==_socket==");
         }
     }
     catch (Exception ex)
     {
         SMSLog.Log("=SocketClient==》StopMe()异常:" + ex.Message);
     }
 }
Example #2
0
 /// <summary>
 /// 启动心跳包
 /// </summary>
 private void HeartStart()
 {
     try
     {
         if (_isStartHeart)
         {
             SMSLog.Log("==启动心跳包=" + DateTime.Now);
             heartSend = new Timer(new TimerCallback(SendHeartCallBack), null, 3000, CMPP_ACTIVE_TEST_C_TICKs * 1000);
             //checkState = new Timer(new TimerCallback(CheckStateCallBack), null, 30000, CMPP_ACTIVE_TCP_TICKs * 1000);
             _threadCheckState = new Thread(new ThreadStart(CheckStateThread));
             _threadCheckState.Start();
         }
         _isStartHeart = false;//只启动一次
     }
     catch (Exception ex)
     {
         SMSLog.Error("【" + _account + "】SocketClient=>启动心跳包=Exception:" + ex.ToString());
     }
 }
Example #3
0
        public void Exit()
        {
            try
            {
                SMSLog.Log("==========SendThread=======Exit=======");
                //thisqueueState.WaitOne();

                try
                {
                    if (_sendtimer != null)
                    {
                        _sendtimer.Dispose();
                    }
                }
                catch (Exception)
                {
                }
                SMSLog.Log("=>SendThread===Exit==_sendtimer...");

                try
                {
                    if (_checkResendtimer != null)
                    {
                        _checkResendtimer.Dispose();
                    }
                }
                catch (Exception)
                {
                }

                SMSLog.Log("=>SendThread===Exit==_checkResendtimer...");


                _socketClient.StopMe();
                SMSLog.Log("=>SendThread===Exit===停止发送线程...");
            }
            catch (Exception ex)
            {
                SMSLog.Error("CmppSendThread==>Exit Exception:" + ex.Message);
            }
            // _isSend = false;
        }
Example #4
0
 //检查状态
 private void CheckStateCallBack(object obj)
 {
     try
     {
         if (((DateTime.Now - this.LastActiveTime).TotalSeconds > CMPP_ACTIVE_TCP_TICKs) && !_isStop)
         {
             this.LastActiveTime = DateTime.Now;
             _isLoginSuccessful  = false;
             SMSLog.Log("CheckStateCallBack......检查状态........重新登录.............=" + DateTime.Now);
             if (!_isLogining)
             {
                 Login();
             }
         }
     }
     catch (Exception ex)
     {
         SMSLog.Error("SocketClient=>CheckStateCallBack()检查状态=>Exception:" + ex.ToString());
     }
 }
Example #5
0
 private void CheckStateThread()
 {
     while (!_isStop)
     {
         try
         {
             checkStateWait.WaitOne(CMPP_ACTIVE_TCP_TICKs * 1000);
             //MyTools.WaitTime(CMPP_ACTIVE_TCP_TICKs*1000);
             if (((DateTime.Now - LastActiveTime).TotalSeconds > CMPP_ACTIVE_TCP_TICKs) && !_isStop)
             {
                 this.LastActiveTime = DateTime.Now;
                 _isLoginSuccessful  = false;
                 SMSLog.Log("CheckStateThread......检查状态........重新登录....begin.........LastActiveTime=" + LastActiveTime);
                 Login();
                 SMSLog.Log("CheckStateThread......检查状态........重新登录.....end........" + DateTime.Now);
             }
         }
         catch (Exception ex)
         {
             SMSLog.Error("SocketClient=>CheckStateThread()检查状态=>Exception:" + ex.ToString());
         }
     }
 }
Example #6
0
        //接收头数据回调
        public void ReciveCallback(IAsyncResult ir)
        {
            SocketError err;
            StateObject state = new StateObject();
            Socket      sok   = null;

            try
            {
                if (ir.IsCompleted)
                {
                    state = ir.AsyncState as StateObject;
                    sok   = state.workSocket;

                    int bytesread = sok.EndReceive(ir, out err);
                    if (bytesread > 0 && err == SocketError.Success)
                    {
                        _isConnectionSuccessful = true;
                        byte[] b = Tools.GetSubBytes(state.buffer, 0, bytesread);
                        //处理数据
                        MemoryStream ms = new MemoryStream(b);
                        BinaryReader br = new BinaryReader(ms);
                        _isConnectionSuccessful = true;
                        Cmpp_HeaderDecode head = new Cmpp_HeaderDecode();
                        head.Decode(br);//解析包头
                        br.Close();
                        ms.Close();
                        Cmpp_Command cmd = (Cmpp_Command)head.Header.Command_Id;
                        if (!Tools.CheckCommand(head.Header.Command_Id))
                        {
                            SMSLog.Error("解析到未知Cmpp_CommandID[重新登录]:" + head.Header.Command_Id.ToString("x8"));
                            // _isLoginSuccessful = false;
                            //Login();
                            return;
                        }



                        try
                        {
                            SMSLog.Debug("接收到:" + cmd + ",cmd=0x" + head.Header.Command_Id.ToString("x8"));
                            if ((head.Header.Total_Length - GlobalModel.HeaderLength) > 0)
                            {
                                byte[] body    = new byte[head.Header.Total_Length - GlobalModel.HeaderLength];
                                int    bodyLen = sok.Receive(body);//接收包体
                                if (bodyLen != head.Header.Total_Length - GlobalModel.HeaderLength)
                                {
                                    SMSLog.Error("接收包体失败[重新登录]:" + head.Header.Command_Id);
                                    // _isLoginSuccessful = false;
                                    //Login();
                                    return;
                                }
                                ms = new MemoryStream(body);
                                br = new BinaryReader(ms);
                            }
                        }
                        catch (Exception ex)
                        {
                            SMSLog.Error("接收包体异常:" + ex.Message);
                        }

                        LastActiveTime = DateTime.Now;//最后一次交互时间
                        switch (cmd)
                        {
                        case Cmpp_Command.CMPP_CONNECT_RESP:
                            Cmpp_LoginDecode login = new Cmpp_LoginDecode();
                            login.Decode(br);
                            if (login.Status == 0)
                            {
                                _isLoginSuccessful = true;
                                this.HeartStart();
                            }
                            else
                            {
                                _isLoginSuccessful = false;
                            }
                            SMSLog.Log("【CMPP_CONNECT_RESP】login=>status=" + login.Status);
                            break;

                        case Cmpp_Command.CMPP_SUBMIT_RESP:
                            try
                            {
                                Cmpp_SubmitDecode sr = new Cmpp_SubmitDecode();
                                sr.Decode(br);
                                SMSLog.Log("【CMPP_SUBMIT_RESP】submit_resp=>result=" + sr.Result + ",msgid=" + sr.MsgId + ",seq=" + head.Header.Sequence_Id);
                                if (GlobalModel.Lparams.IsResend.Equals("1"))
                                {
                                    DelFromWaitingQueueHandler.BeginInvoke(head.Header.Sequence_Id, new AsyncCallback((IAsyncResult) => { }), null);
                                }
                                string[] submitArgs = { head.Header.Sequence_Id + "", sr.MsgId + "", sr.Result + "" };
                                GlobalModel.UpdateSubmitStateHandler.BeginInvoke(submitArgs, new AsyncCallback((IAsyncResult) => { }), null);
                            }
                            catch (Exception ex)
                            {
                                SMSLog.Error("【CMPP_SUBMIT_RESP】异常:" + ex.Message);
                            }
                            break;

                        case Cmpp_Command.CMPP_DELIVER:
                            try
                            {
                                Cmpp_DeliverDecode cd = new Cmpp_DeliverDecode();
                                cd.Decode(br);
                                CMPP_DeliverResp cdresp = new CMPP_DeliverResp(cd.Msg_Id, 0, head.Header.Sequence_Id);
                                this.SendAsync(cdresp.Encode());
                                if (cd.Registered_Delivery == 1)
                                {
                                    SMSLog.Log("【CMPP_DELIVER】CMPP_DELIVER=>stat=" + cd.ReportStat + ",msgid=" + cd.ReportMsgId + ",Dest_Id=" + cd.Dest_Id + ",mobile=" + cd.ReportDestTerminalId + ",seq=" + head.Header.Sequence_Id);
                                    string[] repportArgs = { cd.ReportMsgId + "", cd.Dest_Id, cd.ReportStat, cd.ReportDestTerminalId };
                                    GlobalModel.UpdateReportStateHandler.BeginInvoke(repportArgs, new AsyncCallback((IAsyncResult) => { }), null);
                                }
                                else
                                {
                                    SMSLog.Log("【CMPP_MO】CMPP_DELIVER=>mo=" + cd.Msg_Content + ",msgid=" + cd.ReportMsgId + ",接收Dest_Id=" + cd.Dest_Id + ",来自mobile=" + cd.Src_terminal_Id);
                                    string[] moArgs = { cd.Src_terminal_Id, cd.Dest_Id, cd.Msg_Content };
                                    GlobalModel.SaveMoHandler.BeginInvoke(moArgs, new AsyncCallback((IAsyncResult) => { }), null);
                                }
                            }
                            catch (Exception ex)
                            {
                                SMSLog.Error("【CMPP_DELIVER】异常:" + ex.Message);
                            }
                            break;

                        case Cmpp_Command.CMPP_ACTIVE_TEST:
                            try
                            {
                                CMPP_ActiveTestDecode catde = new CMPP_ActiveTestDecode();
                                catde.Decode(br);
                                CMPP_ActiveTestResp cat = new CMPP_ActiveTestResp();
                                cat.SequenceId = head.Header.Sequence_Id;
                                this.SendAsync(cat.Encode());
                            }
                            catch (Exception)
                            {
                            }
                            break;

                        case Cmpp_Command.CMPP_ACTIVE_TEST_RESP:
                            SMSLog.Log("【CMPP_ACTIVE_TEST_RESP】不处理");
                            //CMPP_ActiveTestDecode catdecode = new CMPP_ActiveTestDecode();
                            //catdecode.Decode(br);
                            //CMPP_ActiveTestResp cata = new CMPP_ActiveTestResp();
                            //cata.SequenceId = head.Header.Sequence_Id;
                            //this.SendAsync(cata.Encode());
                            break;

                        case Cmpp_Command.CMPP_TERMINATE_RESP:
                            SMSLog.Log("【CMPP_TERMINATE_RESP】不处理");
                            //this.HeartStop();
                            //CMPP_TerminateResp tr = new CMPP_TerminateResp();
                            //tr.SequenceId = head.Header.Sequence_Id;
                            //this.SendAsync(tr.Encode());
                            // this._isStop = true;//通知其他线程可以退出了
                            break;

                        case Cmpp_Command.CMPP_TERMINATE:
                            try
                            {
                                SMSLog.Log("【CMPP_TERMINATE】退出命令");
                                _isLoginSuccessful = false;
                                CMPP_TerminateDecode ctrd = new CMPP_TerminateDecode();
                                ctrd.Decode(br);
                                CMPP_TerminateResp ctr = new CMPP_TerminateResp();
                                ctr.SequenceId = head.Header.Sequence_Id;
                                this.SendAsync(ctr.Encode());
                                //this.StopMe();
                            }
                            catch (Exception ex)
                            {
                                SMSLog.Error("【CMPP_TERMINATE】异常:" + ex.Message);
                            }
                            break;

                        default:
                            break;
                        }
                        br.Close();
                        ms.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                SMSLog.Error("【" + _account + "】SocketClient=>ReciveCallback()异常:" + ex.ToString());
            }
            finally
            {
                try
                {
                    if (sok != null)
                    {
                        sok.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, out err, new AsyncCallback(ReciveCallback), state);
                    }
                }
                catch (Exception ex)
                {
                    SMSLog.Error("SocketClient=>再次启动BeginReceive()异常:" + ex.ToString());
                }
            }
        }
Example #7
0
        public override byte[] Encode()
        {
            //head
            CmppHeaderModel head = new CmppHeaderModel();

            head.Command_Id   = (uint)Cmpp_Command.CMPP_CONNECT;
            head.Total_Length = GlobalModel.HeaderLength + 27;
            head.Sequence_Id  = Tools.GetSequence_Id();
            byte[]    headb = this.Header(head);
            ArrayList al    = new ArrayList(headb);

            //body
            byte[] timeStampbytes = this.Uint4ToBytes(_cc.Timestamp);
            string source_addr    = _cc.Source_Addr.Length > 6 ? _cc.Source_Addr.Substring(0, 6) : _cc.Source_Addr;//企业id长度6
            string ts             = _cc.Timestamp.ToString();

            if (ts.Length == 9)
            {
                ts = "0" + ts;
            }

            //f1
            string authenticatorSource = source_addr + "\0\0\0\0\0\0\0\0\0" + _cc.Password + ts;

            byte[] authenticatorSourcebytes_test = Tools.GetMd5Bytes(authenticatorSource);


            //f2 Source_Addr=002122,Timestamp=812184445,Version=20
            // source_addr = "002122";
            // _cc.Password = "******";
            //  ts = "812184445";
            ArrayList aslist = new ArrayList(Encoding.ASCII.GetBytes(source_addr));

            aslist.AddRange(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 });
            aslist.AddRange(Encoding.ASCII.GetBytes(_cc.Password));
            aslist.AddRange(Encoding.ASCII.GetBytes(ts));
            byte[] authenB = aslist.ToArray(typeof(byte)) as byte[];
            MD5    md5     = new MD5CryptoServiceProvider();

            byte[] authenBs = md5.ComputeHash(authenB);
            SMSLog.Log("CMPP_CONNECT==>Source_Addr=" + source_addr + ",Timestamp=" + ts + ",Password="******",authenBs=" + Encoding.ASCII.GetString(authenBs));
            //f3
            byte[] authenticatorSourcebytes = Tools.MakeMd5AuthCode(_cc.Source_Addr, _cc.Password.ToString(), ts);


            byte[] verbyte = Uint1ToBytes(_cc.Version); //new byte[1];
            // verbyte[0] =(byte) _cc.Version;
            // Array.Reverse(verbyte);
            //byte[] sourceb = Encoding.ASCII.GetBytes(source_addr);

            //  byte[] sourceb = new byte[6];
            // byte[] byteaddr=Encoding.ASCII.GetBytes(source_addr);
            // Array.Copy(byteaddr, sourceb, byteaddr.Length);
            //byte[] sourceb = Encoding.ASCII.GetBytes(source_addr);

            al.AddRange(StringToBytes(source_addr, 6));
            //for (int i = 0; i < 6-source_addr.Length;i++ )
            //{
            //    al.AddRange(new byte[] { 0 });
            //}
            al.AddRange(authenBs);
            al.AddRange(verbyte);
            al.AddRange(timeStampbytes);
            byte[] resultbyte = al.ToArray(typeof(byte)) as byte[];

            Console.WriteLine("Source_Addr=" + _cc.Source_Addr + ",Timestamp=" + _cc.Timestamp + ",Version=" + _cc.Version);
            return(resultbyte);
        }