private QueueItem GetMessage() { try { if (_prioritySmsQueue != null && _prioritySmsQueue.Count > 0) { lock (((ICollection)_prioritySmsQueue).SyncRoot) { QueueItem smm = _prioritySmsQueue.Dequeue(); return(smm); } } if (_normalSmsQueue != null && _normalSmsQueue.Count > 0) { lock (((ICollection)_normalSmsQueue).SyncRoot) { QueueItem smm = _normalSmsQueue.Dequeue(); return(smm); } } } catch (System.Exception e) { SMSLog.Error("【" + _accountInfo.eprId + "】SendService.GetMessage()=>Exception:" + e.Message); } // thisqueueState.Set(); return(null); }
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { try { string str = ""; string strDateInfo = "应用程序的主入口点。未处理的异常:" + DateTime.Now.ToString() + "\r\n"; Exception error = e.Exception as Exception; if (error != null) { str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n", error.GetType().Name, error.Message, error.StackTrace); } else { str = string.Format("应用程序线程错误:{0}", e); } MyTools.SendSMS("网关【" + GlobalModel.Lparams.GatewayName + "】ThreadException,请查看状态!"); SMSLog.Error(str); MessageBox.Show("F**K!F**K!F**K!", "Application_ThreadException", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { } }
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 { } }
/// <summary> /// 异步连接 /// </summary> /// <returns></returns> public bool ConnAsync() { try { _isConnectionSuccessful = false; TimeoutObject.Reset(); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(_ip), _port); _socket.BeginConnect(ipe, new AsyncCallback(ConnectCallBack), _socket); if (TimeoutObject.WaitOne(timeoutMSec, false)) { if (_isConnectionSuccessful && _isLoginSuccessful) { _isLogining = false; return(true); } else { SMSLog.Error("【" + _account + "】ConnAsync=====>连接超时"); } } } catch (Exception ex) { _bNre = true; SMSLog.Error("【" + _account + "】conn=====>" + ex.ToString()); } return(false); }
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> /// 同步连接 /// </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); }
/// <summary> /// 异步连接回调,登录 /// </summary> /// <param name="ir"></param> private void ConnectCallBack(IAsyncResult ir) { try { if (ir.IsCompleted) { Socket sok = ir.AsyncState as Socket; if (sok != null && sok.Connected) { sok.EndConnect(ir); _isConnectionSuccessful = true; CmppConnectModel cc = new CmppConnectModel(); cc.Source_Addr = _account; cc.Password = _password; cc.Version = 0x20; cc.Timestamp = Convert.ToUInt32(DateTime.Now.ToString("MMddHHmmss")); Cmpp_Login login = new Cmpp_Login(cc); SendAsync(login.Encode()); Receive(sok); } else { SMSLog.Error("【" + _account + "】====>ConnectCallBack(),连接失败"); } } } catch (Exception ex) { _isConnectionSuccessful = false; SMSLog.Error("【" + _account + "】====>ConnectCallBack()Exception:" + ex.ToString()); } }
//多线程 private void Send(object obj) { try { Submit(); } catch (Exception ex) { SMSLog.Error("CmppSendThread==>Submit Exception:" + ex.Message); } }
private void AddCache(string msgid, SmsModel msg) { try { cache.Add(msgid, msg); } catch (Exception ex) { SMSLog.Error("SMDDatabase::[" + msgid + "],Id=" + msg.id + " AddCache:Exception:", ex.Message); } }
private SmsModel GetFormCache(string msgid) { try { SmsModel obj = cache.Get(msgid) as SmsModel; return(obj); } catch (Exception ex) { SMSLog.Error("SMDDatabase:: GetFormCache:Exception:", ex.Message); } return(null); }
public override List <SqlStatementModel> BatchExec(List <SqlStatementModel> list) { try { SqlErrMsg = ""; return(dal.MsSqlHelper.BatchExec(ConnectionstringLocalTransaction, list)); } catch (SqlException ex) { SqlErrMsg = ex.Message; SMSLog.Error("SqlDBExec =>BatchExec Exception: ", ex.Message); } return(null); }
/// <summary> /// 添加到优先发送队列 /// </summary> /// <param name="sm"></param> public void AddPriorityQueue(QueueItem qi) { try { lock (((ICollection)_prioritySmsQueue).SyncRoot) { _prioritySmsQueue.Enqueue(qi); } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>AddPriorityQueue Exception:" + ex.Message); } }
/// <summary> /// 接收数据 /// </summary> /// <param name="sok"></param> public void Receive(Socket sok) { try { StateObject state = new StateObject(); state.workSocket = sok; SocketError err; sok.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, out err, new AsyncCallback(ReciveCallback), state); } catch (Exception ex) { SMSLog.Error("【" + _account + "】SocketClient=>接收数据异常Receive():" + ex.Message); } }
//单线程 private void Send() { while (_isSend) { try { _manualsend.WaitOne(GlobalModel.Lparams.Senddelay); Submit(); } catch (Exception ex) { SMSLog.Error("CmppSendThread==>Submit Exception:" + ex.Message); } } }
private void DelFromWaitingQueue(uint seq) { try { lock (this._waitingSeqQueue.SyncRoot) { //SMSLog.Debug("从等待队列删除seq:" + seq); this._waitingSeqQueue.Remove(seq); } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>DelFromWaitingQueue: Exception:" + ex.Message); } }
private void DelFromWaitingQueue(QueueItem q) { try { lock (this._waitingSeqQueue.SyncRoot) { //SMSLog.Debug("从等待队列删除QueueItem:" + q.Sequence); this._waitingSeqQueue.Remove(q.Sequence); } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>DelFromWaitingQueue: Exception:" + ex.Message); } }
/// <summary> /// 登录 /// </summary> /// <returns></returns> public bool Login() { try { _socketClient = new SocketClient(_accountInfo.loginname, _accountInfo.password, _accountInfo.serviceIp, _accountInfo.servicePort); _socketClient.DelFromWaitingQueueHandler = this.DelFromWaitingQueue; _socketClient.AccountInfo = _accountInfo; bool b = _socketClient.Login(); return(b); } catch (Exception e) { SMSLog.Error("CmppSendThread==>Login()=>Exception:" + e.Message); } return(false); }
/// <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); } }
/// <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()); } }
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; }
private void AddToWaitingQueue(QueueItem q) { try { lock (this._waitingSeqQueue.SyncRoot) { if (!this._waitingSeqQueue.ContainsKey(q.Sequence)) { //SMSLog.Debug("添加到等待队列:" + q.Sequence); q.InQueueTime = DateTime.Now; q.FailedCount = q.FailedCount + 1; this._waitingSeqQueue.Add(q.Sequence, q); } } } catch (Exception ex) { SMSLog.Error("CmppSendThread==>AddToWaitingQueue: Exception:" + ex.Message); } }
public bool AddSql(SqlStatementModel sm) { bool ret = false; try { lock (((ICollection)sqlueue).SyncRoot) { sqlueue.Enqueue(sm); } ret = true; } catch (Exception ex) { MySqlDBExec.ExecuteNonQuery(sm.CmdTxt, sm.MySqlCmdParms); SMSLog.Error("SMDQueue::addSql", "=================>Exception:" + ex.Message); ret = false; } return(ret); }
//检查状态 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()); } }
private static bool Init() { try { List <string> listWrite = new List <string>() { "192.168.10.58:6379" }; // "192.168.10.58:6379" List <string> readHosts = new List <string>() { GlobalModel.Lparams.RedisUrl }; _pcm = CreateManager(readHosts.ToArray(), listWrite.ToArray(), 0); return(true); } catch (Exception ex) { SMSLog.Error("RedisManager::Init", ex.Message); } return(false); }
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); }
public static T GetVal <T>(string key) { T content = default(T); try { if (_pcm == null) { Init(); } using (var redis = _pcm.GetClient()) { content = redis.Get <T>(key); } } catch (Exception ex) { _pcm = null; SMSLog.Error("RedisManager::GetVal:从redis中取数据异常:", ex.Message); } return(content); }
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()); } } }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { string str = ""; Exception error = e.ExceptionObject as Exception; string strDateInfo = "应用程序的主入口点。未处理的异常:" + DateTime.Now.ToString() + "\r\n"; if (error != null) { str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace); } else { str = string.Format("Application UnhandledError:{0}", e); } MyTools.SendSMS("网关【" + GlobalModel.Lparams.GatewayName + "】UnhandledError,请查看状态!"); SMSLog.Error(str); MessageBox.Show("F**K!F**K!F**K!", "CurrentDomain_Unhandled", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { } }
/// <summary> /// 异步发送 /// </summary> /// <param name="buff"></param> /// <returns></returns> public bool SendAsync(byte[] buff) { try { lock (sendAsynclocker) { if (!_isLoginSuccessful) { // Login(); // MyTools.WaitTime(50); return(false); } if (_socket == null) { _isLoginSuccessful = false; SMSLog.Error("SocketClient=>SendAsync():_socket==null........."); return(false); } if (_socket.Connected == false) { _isLoginSuccessful = false; SMSLog.Error("SocketClient=>SendAsync():_socket未连接........."); return(false); } IAsyncResult ir = _socket.BeginSend(buff, 0, buff.Length, 0, new AsyncCallback(SendAsyncCallback), _socket); return(true); } } catch (Exception ex) { _isLoginSuccessful = false; _isConnectionSuccessful = false; //_bNre = true; SMSLog.Error("SocketClient=>SendAsync():异常" + ex.Message); } return(false); }