public void Close() { try { if (_socket != null) { try { uint seq = Tools.GetSequence_Id(); CMPP_Terminate t = new CMPP_Terminate(); this.Send(t.Encode()); SMSLog.Debug("===Close==发送退出命令======"); // MyTools.WaitTime(100); Thread.Sleep(100); } catch (Exception ex) { SMSLog.Error("Close Error", ex.Message); } _socket.Shutdown(SocketShutdown.Both); _socket.Close(); } } catch { } }
public bool Stop() { SMSLog.Debug("SmsService==>Stop=>开始停止"); GlobalModel.IsStopCollect = true; if (_cstDic != null) { foreach (int key in _cstDic.Keys) { _cstDic[key].Exit(); } } if (ReportQueue != null && ReportQueue.Length > 0) { foreach (SMDQueue smsq in ReportQueue) { smsq.Stop(); } } if (ReportSeqQueue != null && ReportSeqQueue.Length > 0) { foreach (SMDQueue smsq in ReportSeqQueue) { smsq.Stop(); } } SMSLog.Debug("SmsService==>Stop=>已结束..."); return(false); }
/// <summary> /// 同步连接 /// </summary> /// <returns></returns> private Socket Conn() { try { // System.Threading.Interlocked.Increment(ref i); this.Close(); SMSLog.Debug("---------Conn---连接-------------"); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(_ip), _port); IAsyncResult result = sock.BeginConnect(ipe, null, null); //连接 bool success = result.AsyncWaitHandle.WaitOne(1000, false); if (!success) { SMSLog.Debug("---------Conn---连接--超时-----------"); try { sock.Close(); } catch { } throw new SocketException(); } sock.EndConnect(result); _isConnectionSuccessful = true; SMSLog.Debug("---------Conn---连接--成功-----------"); return(sock); } catch (SocketException se) { _isConnectionSuccessful = false; _bNre = true; SMSLog.Error("--------Conn-----连接失败-------Exception:" + se.Message); } return(null); }
public override int ExecuteNonQuery(int cmdType, string cmdText, object commandParameters) { int re = 0; DateTime dt1 = DateTime.Now; try { //SMSGLog.Error(cmdText); SqlErrMsg = ""; MySqlParameter[] cmdParameters = null; if (commandParameters != null) { cmdParameters = commandParameters as MySqlParameter[]; } re = MySqlHelper.ExecuteNonQuery(ConnectionstringLocalTransaction, cmdText, cmdParameters); if ((DateTime.Now - dt1).TotalMilliseconds > 3000) { SMSLog.Debug("SqlDBExec =>ExecuteNonQuery 耗时:" + (DateTime.Now - dt1).TotalMilliseconds + "毫秒,result=" + re + ",sql=" + cmdText); } return(re); } catch (MySqlException ex) { SqlErrMsg = ex.Message; SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception:" + cmdText); SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception: ", ex.Message); } return(0); }
/// <summary> /// 修改ct提交状态,待下次读取 /// </summary> /// <param name="id">内容表id</param> /// <param name="cTSubmitStatus">状态0 可读取,1已发完</param> /// <returns></returns> private void UpdateSMSContentSubmitStatu(string id, int cTSubmitStatus) { string sql = string.Format("update t_sendsms set CTSubmitStatus={0} where Id={1} ", cTSubmitStatus, id); int result = MySqlDBExec.ExecuteNonQuery(sql, null); if (result == 0) { SMSLog.Debug("SmsService==>UpdateSMSContentSubmitStatu[FailSql]:" + sql); } }
/// <summary> /// 删除内容 /// </summary> /// <param name="id">内容表id</param> /// <returns></returns> private void DeleteContent(string id) { string delsql = string.Format("delete from t_sendsms where id={0} and CMSubmitStatus='1' and CUSubmitStatus='1' and CTSubmitStatus='1' ", id); int result = MySqlDBExec.ExecuteNonQuery(delsql, null); if (result == 0) { SMSLog.Debug("SmsService==>DeleteContent[FailSql]:" + delsql); } }
/// <summary> /// 根据批次号修改手机号码表状态 /// </summary> /// <param name="state">状态:0未提交,-1失败,1成功</param> /// <param name="batchnum">批次号</param> /// <param name="errorCode">错误码</param> /// <param name="errMsg">错误说明</param> /// <returns></returns> private void UpdateMobileByBatchNum(int state, string batchnum, string errorCode, string errMsg) { string sql = string.Format("update t_smsmobile_t set SubmitStatus={0},ErrorCode='{1}',Remark='{2}' where BatchNum='{3}'", state, errorCode, errMsg, batchnum); int result = MySqlDBExec.ExecuteNonQuery(sql, null); if (result == 0) { SMSLog.Debug("SmsService==>UpdateSMSContentSubmitStatu[FailSql]:" + sql); } }
public void Stop() { try { queueStatus.WaitOne(); SMSLog.Debug("SMDQueue::Stop", "[" + _title + "]Timer对象停止..."); queueTimer.Change(0, System.Threading.Timeout.Infinite); queueTimer.Dispose();//销毁定时器,即停止定时器 queueTimer = null; } catch //(Exception ex) { } }
/// <summary> /// 更新手机号码提交状态、MSGID /// </summary> /// <param name="id">id</param> /// <param name="state">提交结果</param> /// <param name="msgid">msgid</param> /// <param name="srcno">发送号码</param> /// <returns></returns> private void UpdateMobileSubmitState(string id, string state, string msgid, string remark, string srcno) { int submitstatu = 0; if (state.Equals("0")) { submitstatu = 1; remark = "成功"; } string sql = string.Format("update t_smsmobile_t set MsgId='{0}',SubmitStatus='{1}',ErrorCode='{2}',Remark='{3}',SrcNo='{4}' where id='{5}' ", msgid, submitstatu, state, remark, srcno, id); int re = 0; int i = 0; do { re = MySqlDBExec.ExecuteNonQuery(sql, null); i++; } while (re <= 0 && i < 3); if (re < 1) { SMSLog.Debug("SmsService==>UpdateMobileSubmitState[FailSql]:" + sql); } //重新加入缓存 SmsModel sm = this.GetFormCache(id); if (sm != null) { this.AddCache(msgid, sm); } //失败状态,写入状态流水表 if (submitstatu == 0) { if (sm != null) { object[] obj = { sm.eprId, sm.userId, sm.mobile, sm.clientMsgId, submitstatu }; string sqlstate = string.Format("insert into t_pushsmsmsg(EprId,UserId,Mobile,ClientMsgId,Status,AddTime) values('{0}','{1}','{2}','{3}','{4}',now())", obj); Random rand = new Random(); int ii = rand.Next(0, _reportQueueNum + 1); SqlStatementModel seq = new SqlStatementModel(); seq.MySqlCmdParms = null; seq.CmdTxt = sqlstate; seq.CmdType = CommandType.Text; seq.ExecTimer = 1; ReportSeqQueue[ii].AddSql(seq); } } }
private bool FillMessage(DataRow row, SmsModel msg) { try { msg.id = UInt32.Parse(row["Id"].ToString());//消息ID msg.batchNum = row["BatchNum"].ToString(); msg.eprId = int.Parse(row["EprId"].ToString()); msg.mobile = row["Mobile"].ToString(); //手机号码 return(true); } catch (Exception ex) { SMSLog.Debug("SmsService==>FillMessage[Exception]:" + ex.Message); } return(false); }
public static DataTable GetDateTable(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { try { DateTime dt1 = DateTime.Now; DataTable ds = MsSqlHelper.GetDateTable(ConnectionstringLocalTransaction, cmdType, cmdText, commandParameters); if ((DateTime.Now - dt1).TotalMilliseconds > 3000) { SMSLog.Debug("SqlDBExec =>GetDateTable 耗时:" + (DateTime.Now - dt1).TotalMilliseconds + "毫秒"); } return(ds); }catch (SqlException ex) { } return(null); }
/// <summary> /// 心跳包 /// </summary> /// <param name="obj"></param> private void SendHeartCallBack(object obj) { try { if (IsPingTime() && !_isStop) { CMPP_ActiveTest heart = new CMPP_ActiveTest(); this.Send(heart.Encode()); SMSLog.Debug("SocketClient=>发送心跳包......"); } } catch (Exception ex) { SMSLog.Error("【" + _account + "】SocketClient=>发送心跳包异常:SendAsync():" + ex.Message); } }
private void CheckReSend(object obj) { try { for (int i = 0; i < this._waitingSeqQueue.Count; i++) { QueueItem q = (QueueItem)_waitingSeqQueue.GetByIndex(i); if (q != null) { DateTime this_time = DateTime.Now; //去当前时间 TimeSpan t = this_time - q.InQueueTime; if (t.TotalSeconds > MASG_TIMEOUT_TICKs) //达到超时时间 { this.DelFromWaitingQueue(q); //从等待队列中删除 //需要重新发送消息 if (q.FailedCount >= CMPP_ACTIVE_TEST_N_COUNT) { //报告消息发送失败 //GlobalModel.UpdateMobileSubmitStateHandler.BeginInvoke(q.Sequence + "", "-1", "", "提交失败", "", new AsyncCallback((IAsyncResult ar) => { }), null); string[] args = { q.Sequence + "", "", "31010", "超过最大重发次数", "" }; GlobalModel.UpdateSubmitStateHandler.BeginInvoke(args, new AsyncCallback((IAsyncResult ar) => { }), null); // q.MsgState =(int)MSG_STATE.SENDED_WAITTING; } else { //尝试再次发送 q.InQueueTime = this_time; q.FailedCount++; q.MsgState = (int)MSG_STATE.SENDED_WAITTING; SMSLog.Debug("从等待队列==》添加到待发队列:" + q.Sequence); this.AddNormalQueue(q); } } else { break; } } } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>CheckReSend: Exception:" + ex.Message); } }
public bool Start() { try { _prioritySmsQueue = new Queue <QueueItem>(); _normalSmsQueue = new Queue <QueueItem>(); //_socketClient = new SocketClient(_accountInfo.loginname, _accountInfo.password); // _socketClient.WriteLogHandler = WriteLogHandler; //_socketClient.ConnAsync();//连接,登录 object sendLock = new object(); //多线程 // TimerCallback tc = new TimerCallback(Send); // _sendtimer = new Timer(tc, sendLock, 10, GlobalModel.Lparams.Senddelay); //单线程 _sendthread = new Thread(new ThreadStart(Send)); _sendthread.IsBackground = true; _sendthread.Start(); if (GlobalModel.Lparams.IsResend.Equals("1")) { _checkResendtimer = new Timer(new TimerCallback(CheckReSend), sendLock, 10, 10000); SMSLog.Debug("CmppSendThread==>Start CheckReSend..........."); } else { SMSLog.Debug("CmppSendThread==>Start不重复提交!"); } return(true); } catch (Exception ex) { _isSend = false; SMSLog.Error("CmppSendThread==>Start Exception:" + ex.Message); } return(false); }
private void SaveMo(int eprId, string mobile, string recvnumber, string content) { string userId = ""; string client_msgid = ""; int IsPush = 0; string sel = string.Format("select * from t_smsmobile_t where EprId='{0}' and Mobile='{1}' order by SendTime desc limit 1", eprId, mobile); DataTable dt = MySqlDBExec.GetDateTable(sel, null); if (dt != null && dt.Rows.Count > 0) { userId = dt.Rows[0]["UserID"].ToString(); client_msgid = dt.Rows[0]["ClientMsgId"].ToString(); } object[] obj = { eprId, userId, "", mobile, recvnumber, DateTime.Now.ToString(), content, 1, IsPush, DateTime.Now.ToString(), 0, client_msgid }; string insql = string.Format("insert into t_morecord(EprId,UserId,Name,SendNum,RecvNum,RecvTime,Content,IsNew,IsPush,AddTime,IsDel,ClientMsgId) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", obj); int re = MySqlDBExec.ExecuteNonQuery(insql, null); if (re < 1) { SMSLog.Debug("SmsService==>SaveMo[FailSql]:" + insql); } }
public static int ExecuteNonQuery(string cmdText) { int re = 0; DateTime dt1 = DateTime.Now; try { //SMSGLog.Error(cmdText); SqlErrMsg = ""; re = MsSqlHelper.ExecuteNonQuery(ConnectionstringLocalTransaction, CommandType.Text, cmdText, null); if ((DateTime.Now - dt1).TotalMilliseconds > 3000) { SMSLog.Debug("SqlDBExec =>ExecuteNonQuery 耗时:" + (DateTime.Now - dt1).TotalMilliseconds + "毫秒,result=" + re + ",sql=" + cmdText); } return(re); } catch (SqlException ex) { SqlErrMsg = ex.Message; SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception:" + cmdText); SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception: ", ex.Message); } return(0); }
/// <summary> /// 启动Timer对象,定时保存数据 /// </summary> /// <param name="duttime"></param> public void Start(int duttime) { System.Threading.TimerCallback saveQueue = new System.Threading.TimerCallback(BatchSaveSql); queueTimer = new System.Threading.Timer(saveQueue, null, duttime, duttime); SMSLog.Debug("SMDQueue::Start", "启动[" + _title + "]对象,定时[" + duttime + "]保存数据"); }
public void AddQueue(int eprId, SmsModel sms) { bool ispriority = false; foreach (string str in Keyword) { if (sms.content.Contains(str)) { ispriority = true; break; } } QueueItem qi = new QueueItem(); qi.InQueueTime = DateTime.Now; qi.MsgObj = sms; qi.MsgState = 0; qi.MsgType = (uint)Cmpp_Command.CMPP_SUBMIT; qi.Sequence = sms.id; if (_cstDic.ContainsKey(eprId)) { if (ispriority) { _cstDic[eprId].AddPriorityQueue(qi); } else { _cstDic[eprId].AddNormalQueue(qi); } } else { AccountInfoModel ai = this.GetAccountInfo(sms.eprId); if (ai != null) { SendThread cmpp = new SendThread(ai); if (cmpp.Login()) { if (!_cstDic.ContainsKey(ai.eprId)) { _cstDic.Add(ai.eprId, cmpp); } if (!_cmppAccountDic.ContainsKey(ai.eprId)) { _cmppAccountDic.Add(ai.eprId, ai); } cmpp.AddPriorityQueue(qi); cmpp.IsSend = true; cmpp.Start(); } else { this.DeleteContent(sms.contentId); UpdateMobileSubmitState(sms.id + "", "-1", "", "CMPP账号登录失败", ""); SMSLog.Debug("SmsService==>AddQueue[" + ai.eprId + "]登录失败"); } } else { this.DeleteContent(sms.contentId); UpdateMobileSubmitState(sms.id + "", "-1", "", "无CMPP账号", ""); } } }
private void CollectThread(object obj) { if (GlobalModel.IsStopCollect) { return; } string sql = GetLoadMessageSql(); if (!string.IsNullOrEmpty(sql)) { DataTable dt = MySqlDBExec.GetDateTable(sql, null); if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { string CTGatewayNum = dt.Rows[i]["CTGatewayNum"].ToString(); string id = dt.Rows[i]["Id"].ToString(); string batchnum = dt.Rows[i]["BatchNum"].ToString(); string eprId = dt.Rows[i]["EprId"].ToString(); string con = dt.Rows[i]["Content"].ToString();//短信内容 int mobileCount = 0; int.TryParse(dt.Rows[i]["MobileCount"].ToString(), out mobileCount); if (CTGatewayNum.Equals("1001")) { SMSLog.Debug("SMDDatabase==>该批次号[" + batchnum + "]1001不发送,修改tcsubmitstate状态为1 并试图删除"); UpdateSMSContentSubmitStatu(id, 1); this.DeleteContent(id); UpdateMobileByBatchNum(-1, batchnum, "1001", "限制网关"); continue; } DataTable dt_mobile = this.LoadMobile(batchnum);//根据批次号取发送号码 if (dt_mobile != null && dt_mobile.Rows.Count > 0) { for (int j = 0; j < dt_mobile.Rows.Count; j++) { SmsModel msg = new SmsModel(); msg.content = con; //短信内容 msg.contentId = id; //内容表ID if (FillMessage(dt_mobile.Rows[j], msg)) { AddQueue(msg.eprId, msg); //加入待发队列 AddCache(msg.id + "", msg); //加入缓存 } } if (dt_mobile.Rows.Count <= mobileCount) { SMSLog.Debug("SMDDatabase==>该批次号[" + batchnum + "]已读取完,修改tcsubmitstate状态为1 并试图删除"); UpdateSMSContentSubmitStatu(id, 1); this.DeleteContent(id); } else { UpdateSMSContentSubmitStatu(id, 0);//改变状态,待下次读取 } } else { try { SMSLog.Debug("SMDDatabase==>无该批次号[" + batchnum + "]手机号码,修改tcsubmitstate状态为1 并试图删除"); UpdateSMSContentSubmitStatu(id, 1); this.DeleteContent(id); } catch (Exception ex) { SMSLog.Error("SMDDatabase::CollectThread", "删除异常: " + ex.Message); } } }//for } } }
//接收头数据回调 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()); } } }
public DataTable GetMessageFromActiveMQ(int count) { lock (getmsglock) { if (consumer == null) { throw new Exception("consumer==null"); } DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("ID")); dt.Columns.Add(new DataColumn("UCUID")); dt.Columns.Add(new DataColumn("MOBILE")); dt.Columns.Add(new DataColumn("CID")); dt.Columns.Add(new DataColumn("CLIENTMSGID")); dt.Columns.Add(new DataColumn("EXTNUM")); dt.Columns.Add(new DataColumn("CONTENT")); dt.Columns.Add(new DataColumn("SNDID")); dt.Columns.Add(new DataColumn("EPRID")); StringBuilder sbg = new StringBuilder(); for (int i = 0; i < count; i++) { try { ITextMessage msg = consumer.ReceiveNoWait() as ITextMessage; if (msg == null) { break; } else { string txt = dataid + "," + msg.Text; dataid++; //SMSLog.Debug("【从ActiveMQ取到数据】" + txt); sbg.AppendLine(txt); string[] args = txt.Split(new char[] { ',' }); if (args.Length != 8) { SMSLog.Error("ActiveMQClient::GetMessageFromActive==>【读取内容 Exception】", "args.len!=8"); continue; } string cid = args[3]; DateTime dt1 = DateTime.Now; string content = RedisManager.GetVal <string>("sms" + cid); if (string.IsNullOrEmpty(content)) { try { string sql = string.Format("select content from TBL_SMS_CONTENT where ID={0}", cid); SMSLog.Error("ActiveMQClient=====redis===== 未取到内容==" + sql); object obj = _dbexec.ExecuteScalar(sql); content = obj == null ? "" : obj.ToString(); } catch (Exception ex) { SMSLog.Error("ActiveMQClient::GetMessageFromActive==>读取内容 Exception:", ex.ToString()); } } // SMSLog.Debug("ActiveMQClient", "读取内容用时[" + (DateTime.Now - dt1).TotalMilliseconds + "]毫秒"); if (!string.IsNullOrEmpty(content)) { content = MyTools.NoHTML(content); DataRow dr = dt.NewRow(); dr["ID"] = args[0]; dr["UCUID"] = args[1]; dr["MOBILE"] = args[2]; dr["CID"] = cid; dr["CLIENTMSGID"] = args[4]; dr["EXTNUM"] = args[5]; dr["SNDID"] = args[6]; dr["EPRID"] = args[7]; dr["CONTENT"] = content; dt.Rows.Add(dr); //msg.Acknowledge(); } else { SMSLog.Error("ActiveMQClient::GetMessageFromActive", "没取到内容[" + cid + "]"); } } } catch (Exception ex) { SMSLog.Error("ActiveMQClient::GetMessageFromActive==>for Exception:", ex.ToString()); } }//for try { if (!string.IsNullOrEmpty(sbg.ToString()) && sbg.Length > 10) { SMSLog.Debug(sbg.ToString()); } } catch { } return(dt); } }
/// <summary> /// 同步登录 /// </summary> /// <returns></returns> public bool Login() { lock (loginlocker) { try { SMSLog.Debug("Login==>begin..."); Socket sock; try { if (_isStop) { SMSLog.Debug("Login==>已停止不再登录..."); return(false); } if (_isLoginSuccessful) { SMSLog.Debug("Login==>已登录成功..."); return(true); } if (_isLogining) { SMSLog.Debug("Login==>正在登录..."); return(false); } _isLogining = true; sock = this.Conn(); GlobalModel.IsLogin = false; if (sock == null) { SMSLog.Error("SocketClient==>Login()...sock连接短信中心失败...."); if (sendsmstimes < 1) { // MyTools.SendSMS("网关[" + GlobalModel.Lparams.GatewayName + "]连接短信中心失败"); sendsmstimes++; } _isLogining = false; return(false); } //发送登录验证包 //uint seq = Tools.GetSequence_Id(); //取得一个流水号 CmppConnectModel cc = new CmppConnectModel(); cc.Source_Addr = _account; cc.Password = _password; cc.Version = (uint)GlobalModel.Lparams.Version;//0x20 cc.Timestamp = Convert.ToUInt32(DateTime.Now.ToString("MMddHHmmss")); Cmpp_Login login = new Cmpp_Login(cc); int sendlen = sock.Send(login.Encode()); SMSLog.Debug("连接成功发送登录包[" + sendlen + "]..."); if (!sock.Poll(1000000, SelectMode.SelectWrite)) { SMSLog.Error("=>cmpp::Login", "短信中心超时未应答,登录失败!"); sock.Close(); return(_isLogining = false); } } catch (SocketException se) { SMSLog.Error("登录异常【" + _account + "】:" + se.Message); _isLogining = false; return(_isLogining = false); } DateTime t1 = DateTime.Now; byte[] rbuf = new Byte[400]; int l; try { l = sock.Receive(rbuf); SMSLog.Debug("接收到数据长度:" + l); if (l > 16) { MemoryStream ms = new MemoryStream(rbuf); BinaryReader br = new BinaryReader(ms); Cmpp_HeaderDecode head = new Cmpp_HeaderDecode(); head.Decode(br);//解析包头 SMSLog.Debug(head.Header.Command_Id + ""); if ((Cmpp_Command)head.Header.Command_Id == Cmpp_Command.CMPP_CONNECT_RESP) { Cmpp_LoginDecode login = new Cmpp_LoginDecode(); login.Decode(br); if (login.Status == 0) { _isLoginSuccessful = true; SMSLog.Debug("登录成功:[" + _account + "],version=0x" + login.Version.ToString("x8")); this.LastActiveTime = DateTime.Now; //更新当前最后成功收发套接字的时间 } else { _isLoginSuccessful = false; SMSLog.Error("登录失败:[" + _account + "],result=" + login.Status); } } } } catch (SocketException ex) { _isLoginSuccessful = false; SMSLog.Error("登录接收异常:" + ex.Message); if (sock != null) { sock.Close(); } } if (this._isLoginSuccessful) { sendsmstimes = 0; this.LastActiveTime = DateTime.Now; _socket = sock; MyTools.StopThread(_threadReceive); _threadReceive = new Thread(new ThreadStart(() => { Receive(_socket); })); _threadReceive.Start(); //登录ok,就立即发送active_test包 CMPP_ActiveTest heart = new CMPP_ActiveTest(); this.Send(heart.Encode()); GlobalModel.IsLogin = true; // 启动 主监视程序de线程 this.HeartStart(); _isLogining = false; return(true); } else { if (sendsmstimes < 1) { MyTools.SendSMS("网关[" + GlobalModel.Lparams.GatewayName + "]登录失败"); sendsmstimes++; } sock.Shutdown(SocketShutdown.Both); sock.Close(); _isLogining = false; return(false); } } catch (Exception ex) { SMSLog.Error("登录异常:" + ex.Message); } finally { _isLogining = false; } return(false); } }
private void Submit() { try { //if (!_socketClient.IsLogin) //{ // GlobalModel.WaitSendQueue.Set(); // //thisqueueState.Set(); // continue; //} //if (GlobalModel.ServiceIsStop) //{ // GlobalModel.WaitSendQueue.Set(); // continue; //} QueueItem qi = this.GetMessage(); //if(i==0) //{ // qi = new QueueItem(); // SmsModel s = new SmsModel(); // s.content = "【比亚迪】您好!400客服接到F3用户王文刚(13842636503)其它,需要贵店给予支持,详情请查阅CRM派单信息1,详情请查阅CRM派单信息2,详情请查阅CRM派单信息3!"; // s.content = "【比亚迪】Hello World!"; // s.mobile = "13682488577"; // s.id = 1; // s.subId = "123"; // qi.MsgObj = s; // i++; //} if (qi == null) { GlobalModel.WaitSendQueue.Set(); //thisqueueState.Set(); return; } SmsModel sms = qi.MsgObj as SmsModel; if (sms != null) { bool b = false; try { if (!MyTools.IsFirstsign(sms.content) && !MyTools.IsLastsign(sms.content)) { SMSLog.Debug("CmppSendThread=>Send无签名[" + sms.id + "]to[" + sms.mobile + "]content=" + sms.content); GlobalModel.TransferDataProcHandler.BeginInvoke((int)sms.id, sms.operatorId, 31013, "", new AsyncCallback((IAsyncResult) => { }), null); return; } if (!MyTools.IsFirstsign(sms.content) && MyTools.IsLastsign(sms.content)) { sms.content = MyTools.SignBefore(sms.content); } //SMSLog.Debug("CmppSendThread=>Send[" + sms.id + "][" + sms.srcnum + "]to[" + sms.mobile + "]content=" + sms.content); string srcid = sms.srcnum;//显示号码 string con = sms.content.Trim(); int msgnum = 1; if (con.Length < 71) { msgnum = 1; } else { msgnum = (int)Math.Ceiling(con.Length / 67.0); } //SMSLog.Debug("CmppSendThread=>msgnum=[" + msgnum + "]"); if (msgnum > 1) { CmppSubmitLongModel sub = new CmppSubmitLongModel(); sub.Sequence_Id = sms.id; sub.Msg_Id = Tools.Timestamp(); sub.Pk_total = (uint)msgnum; sub.Registered_Delivery = 1; sub.Msg_level = 0; sub.Service_Id = GlobalModel.Lparams.ServiceId;//_accountInfo.serviceid; sub.Fee_UserType = 2; sub.Fee_terminal_Id = 0; sub.TP_pId = 0; sub.TP_udhi = 1; sub.Msg_Fmt = (uint)MsgContentFormat.UCS2; sub.Msg_src = GlobalModel.Lparams.Spid;// _accountInfo.spid; sub.FeeType = "02"; sub.FeeCode = "000001"; sub.At_Time = ""; sub.ValId_Time = Tools.GetValIdTime(DateTime.Now); sub.Src_Id = srcid; sub.DestUsr_tl = 1; sub.Dest_terminal_Id = sms.mobile; sub.Reserve = ""; string[] msgarr = Tools.GetMsgArray(67, con); string[] scontent = msgarr; //SMSLog.Error("SendThread==>Send==>【msgarr】" + msgarr.Length); int iLength = msgarr.Length; int m_LongMsg = 70; string lastMsg = msgarr[iLength - 1]; if (lastMsg.Length > m_LongMsg) { iLength = iLength + 1; scontent = new string[iLength]; for (int i = 0; i < (iLength - 2); i++) { scontent[i] = msgarr[i]; } string[] stmp = Tools.GetMsgArray(m_LongMsg, lastMsg); scontent[iLength - 2] = stmp[0]; scontent[iLength - 1] = stmp[1]; } else { scontent = msgarr; } for (int i = 0; i < scontent.Length; i++) { try { string splitcon = scontent[i]; sub.Pk_number = (uint)(i + 1); sub.Msg_Length = (uint)(Encoding.BigEndianUnicode.GetBytes(splitcon).Length + 6);//内容长度+6字节头 sub.Msg_Content = splitcon; Cmpp_SubmitLong cs = new Cmpp_SubmitLong(sub); byte[] byt = cs.Encode(); b = _socketClient.SendAsync(byt); SMSLog.Debug("SendThread=>Send[" + b + "] Hex[" + sms.id + "]to[" + sms.mobile + "]index=" + i + ",extnum=" + srcid + ",content=" + splitcon); //SMSLog.Debug("SendThread=>Send Hex[" + MyTools.ByteToHex(byt) + "]", false); if (b) { longMsgWait.WaitOne(10); //MyTools.WaitTime(10); } else { break; } } catch (Exception ex) { SMSLog.Error("SendThread==>Send==>【(for)SendAsync 发送异常:】" + ex.ToString()); } } } else { CmppSubmitModel sub = new CmppSubmitModel(); try { sub.Sequence_Id = sms.id; sub.Msg_Id = Tools.Timestamp(); sub.Pk_total = 1; sub.Pk_number = 1; sub.Registered_Delivery = 1; sub.Msg_level = 0; sub.Service_Id = GlobalModel.Lparams.ServiceId;// _accountInfo.serviceid; sub.Fee_UserType = 2; sub.Fee_terminal_Id = 0; sub.TP_pId = 0; sub.TP_udhi = 0; sub.Msg_Fmt = (uint)MsgContentFormat.UCS2; sub.Msg_src = GlobalModel.Lparams.Spid;// _accountInfo.spid; sub.FeeType = "02"; sub.FeeCode = "000001"; sub.At_Time = ""; sub.ValId_Time = Tools.GetValIdTime(DateTime.Now); sub.Src_Id = srcid; sub.DestUsr_tl = 1; sub.Dest_terminal_Id = sms.mobile; sub.Msg_Length = (uint)Encoding.BigEndianUnicode.GetBytes(sms.content.Trim()).Length; sub.Msg_Content = sms.content; sub.Reserve = ""; } catch (Exception ex) { SMSLog.Error("SendThread==>_socketClient==>sub 发送异常:" + ex.StackTrace); } try { Cmpp_Submit cs = new Cmpp_Submit(sub); byte[] byt = cs.Encode(); b = _socketClient.SendAsync(byt); SMSLog.Debug("SendThread=>Send[" + b + "] Hex[" + sms.id + "]to[" + sms.mobile + "],extnum=" + srcid + ",content=" + sms.content); //SMSLog.Debug("SendThread=>Send Hex[" + MyTools.ByteToHex(byt) + "]", false); } catch (Exception ex) { SMSLog.Error("SendThread==>_socketClient==>SendAsync 【发送异常】:" + ex.ToString()); } } } catch (Exception ex) { b = false; SMSLog.Error("SendThread==>Send 【发送异常】:" + ex.Message); } try { if (b) { qi.MsgState = (int)MSG_STATE.SENDED_WAITTING; GlobalModel.TransferDataProcHandler.BeginInvoke((int)sms.id, sms.operatorId, 0, "", new AsyncCallback((IAsyncResult) => { }), null); if (GlobalModel.Lparams.IsResend.Equals("1")) { AddToWaitingQueue(qi);//添加到等待队列 } } else { if (qi.FailedCount < 3) { qi.FailedCount++; this.AddPriorityQueue(qi); SMSLog.Debug("提交失败重新加入队列:CID=" + sms.cid + ",mobile=" + sms.mobile + ",CONTENT=" + sms.content); } else { GlobalModel.TransferDataProcHandler.BeginInvoke((int)sms.id, sms.operatorId, 31999, "", new AsyncCallback((IAsyncResult) => { }), null); } } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>Send 转移异常:" + ex.Message); } } else { GlobalModel.WaitSendQueue.Set(); } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>Send Exception:" + ex.Message); } }
/// <summary> /// 批量保存 /// </summary> /// <returns></returns> private void BatchSaveSql(object obj) { try { List <SqlStatementModel> sqlList = new List <SqlStatementModel>(); try { if (sqlueue != null && sqlueue.Count > 0) { lock (((ICollection)sqlueue).SyncRoot) { for (int i = 0; i < _maxexecnum; i++) { if (i > sqlueue.Count) { break; } SqlStatementModel sm = sqlueue.Dequeue(); if (sm != null) { sqlList.Add(sm); } else { break; } } } } else { queueStatus.Set(); } } catch (Exception ex) { SMSLog.Error("SMDQueue::BatchSaveSql(Dequeue):Exception:", ex.Message); } if (sqlList != null && sqlList.Count > 0) { DateTime tmStart = DateTime.Now; List <SqlStatementModel> reList = dbexec.BatchExec(sqlList); int re = 0; if (reList != null) { re = reList.Count; foreach (SqlStatementModel resm in reList) { resm.ExecTimer++; if (resm.ExecTimer < _maxexectimer) { SMSLog.Debug("SMDQueue==>BatchSaveSql=>Result Fail[" + resm.ExecTimer + "]" + resm.ToString()); this.AddSql(resm); } else { if (resm.CmdType == System.Data.CommandType.Text) { SMSLog.Debug("SMDQueue==>BatchSaveSql[FailSql]:" + resm.ToString()); } else { SMSLog.Debug("SMDQueue==>BatchSaveSql[FailProc]:" + resm.ToString()); } } } } SMSLog.Debug("SMDQueue::BatchSaveSql", " BatchExcSql (" + sqlList.Count + "),Result Fail:" + re + "]时间: " + (DateTime.Now - tmStart).TotalMilliseconds + "毫秒"); } } catch (Exception EX) { SMSLog.Error("SMDQueue::BatchSaveSql:Exception:", EX.Message); } }
public bool Start() { lp = new LocalParams(); if (!dbexec.IsConn(lp.SqlConnStr)) { SMSLog.Debug("SmsService==>Init=>sql登录失败[" + lp.SqlConnStr + "]"); return(false); } MySqlDBExec.ConnectionstringLocalTransaction = lp.SqlConnStr; _cstDic = new Dictionary <int, SendThread>(); _cmppAccountDic = new Dictionary <int, AccountInfoModel>(); //初始数据标识 string sql1 = "update t_sendsms set CTSubmitStatus=0 Where CTGatewayNum='" + lp.GateWayNum + "'"; string sql2 = "update t_smsmobile_t set smsFlag='0' where SubmitStatus='0' and GatewayNum='" + lp.GateWayNum + "'"; int re1 = MySqlDBExec.ExecuteNonQuery(sql1, null); SMSLog.Debug("SmsService==>Init初始内容表:" + re1); int re2 = MySqlDBExec.ExecuteNonQuery(sql2, null); SMSLog.Debug("SmsService==>Init初始手机号码表:" + re2); cache = new TimeoutCache(60 * 30);//缓存 ReportQueue = new SMDQueue[_reportQueueNum]; ReportSeqQueue = new SMDQueue[_reportQueueNum]; for (int i = 0; i < _reportQueueNum; i++) { string title = "Report_" + i; ReportQueue[i] = new SMDQueue(title); ReportQueue[i].Start(3000); string seqt = "ReportSeq_" + i; ReportSeqQueue[i] = new SMDQueue(seqt); ReportSeqQueue[i].Start(4000); } /* * GlobalModel.UpdateMobileSubmitStateHandler = this.UpdateMobileSubmitState; * GlobalModel.UpdateReportStateHandler = this.UpdateReportState; * GlobalModel.UpdateMobileByBatchNumHandler = this.UpdateMobileByBatchNum; * GlobalModel.UpdateSMSContentSubmitStatuHandler = this.UpdateSMSContentSubmitStatu; * GlobalModel.DeleteContentHandler = this.DeleteContent; * GlobalModel.SaveMoHandler = this.SaveMo; * */ //读取企业CMPP账号信息 List <AccountInfoModel> accountLst = LoadCmppAccount(); if (accountLst != null && accountLst.Count > 0) { foreach (AccountInfoModel m in accountLst) { SendThread cmpp = new SendThread(m); if (cmpp.Login()) { _cstDic.Add(m.eprId, cmpp); _cmppAccountDic.Add(m.eprId, m); cmpp.IsSend = true; cmpp.Start(); } else { SMSLog.Debug("SmsService==>Init[" + m.eprId + "]登录失败"); } Thread.Sleep(10); } } else { SMSLog.Debug("SmsService==>[Init]读取cmpp账号失败"); return(false); } GlobalModel.IsStopCollect = false; CollectObject_Business co = new CollectObject_Business(); _collDataTimer = new Timer(new TimerCallback(CollectThread), co, lp.ReadContentDealy, lp.ReadContentDealy); SMSLog.Debug("SmsService==>[Init]启动成功"); return(true); }