From bce98592d544b64cf11dece9c7f47b7e7de238c7 Mon Sep 17 00:00:00 2001 From: renyh1013 Date: Wed, 25 May 2016 00:07:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=B0=8F=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestMessage/Form1.Designer.cs | 14 -- TestMessage/Form1.cs | 140 ++--------------- TestMessage/TestMessage.csproj | 1 - TestMessage/myMsgHandler.cs | 24 --- dp2Message/BaseMsgHandler.cs | 267 ++++++++++++++++----------------- 5 files changed, 138 insertions(+), 308 deletions(-) delete mode 100644 TestMessage/myMsgHandler.cs diff --git a/TestMessage/Form1.Designer.cs b/TestMessage/Form1.Designer.cs index 03805285..8e45a69f 100644 --- a/TestMessage/Form1.Designer.cs +++ b/TestMessage/Form1.Designer.cs @@ -30,7 +30,6 @@ private void InitializeComponent() { this.textBox_message_groupName = new System.Windows.Forms.TextBox(); this.label38 = new System.Windows.Forms.Label(); - this.button_message_send = new System.Windows.Forms.Button(); this.textBox_config_password = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox_config_userName = new System.Windows.Forms.TextBox(); @@ -59,16 +58,6 @@ private void InitializeComponent() this.label38.TabIndex = 40; this.label38.Text = "Group Name:"; // - // button_message_send - // - this.button_message_send.Location = new System.Drawing.Point(23, 123); - this.button_message_send.Name = "button_message_send"; - this.button_message_send.Size = new System.Drawing.Size(145, 23); - this.button_message_send.TabIndex = 42; - this.button_message_send.Text = "Send 100条message"; - this.button_message_send.UseVisualStyleBackColor = true; - this.button_message_send.Click += new System.EventHandler(this.button_message_send_Click); - // // textBox_config_password // this.textBox_config_password.Location = new System.Drawing.Point(324, 50); @@ -164,12 +153,10 @@ private void InitializeComponent() this.Controls.Add(this.label2); this.Controls.Add(this.textBox_config_messageServerUrl); this.Controls.Add(this.label1); - this.Controls.Add(this.button_message_send); this.Controls.Add(this.textBox_message_groupName); this.Controls.Add(this.label38); this.Name = "Form1"; this.Text = "Form1"; - this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); @@ -179,7 +166,6 @@ private void InitializeComponent() private System.Windows.Forms.TextBox textBox_message_groupName; private System.Windows.Forms.Label label38; - private System.Windows.Forms.Button button_message_send; private System.Windows.Forms.TextBox textBox_config_password; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox_config_userName; diff --git a/TestMessage/Form1.cs b/TestMessage/Form1.cs index a136eb7a..7c56a2e4 100644 --- a/TestMessage/Form1.cs +++ b/TestMessage/Form1.cs @@ -6,6 +6,7 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -18,19 +19,22 @@ public partial class Form1 : Form { MessageConnectionCollection _channels = new MessageConnectionCollection(); - myMsgHandler msgHandler = null; + BaseMsgHandler msgHandler = null; public Form1() { InitializeComponent(); - _channels.Login += _channels_Login; + string logDir="c:/msg_data"; + if (Directory.Exists(logDir) == false) + { + Directory.CreateDirectory(logDir); + } - msgHandler = new myMsgHandler(); + msgHandler = new BaseMsgHandler(); msgHandler.Init(this._channels, - "http://localhost:8083/dp2mserver", - "c:/msg_data"); - msgHandler.form = this; + this.textBox_config_messageServerUrl.Text.Trim(), //"http://localhost:8083/dp2mserver", + logDir); } void _channels_Login(object sender, LoginEventArgs e) @@ -42,142 +46,18 @@ void _channels_Login(object sender, LoginEventArgs e) throw new Exception("尚未指定用户名,无法进行登录"); e.Password = GetPassword(); - e.Parameters = "propertyList=biblio_search,libraryUID=xxx"; } string GetUserName() { -#if NO - if (this.InvokeRequired) - return (string)this.Invoke(new Func(GetUserName)); - else -#endif return this.textBox_config_userName.Text; } - string GetPassword() { -#if NO - if (this.InvokeRequired) - return (string)this.Invoke(new Func(GetPassword)); - else -#endif return this.textBox_config_password.Text; } - private void button_message_send_Click(object sender, EventArgs e) - { - DoSendMessage(this.textBox_message_groupName.Text,""); - } - - - - async void DoSendMessage(string strGroupName, string strText) - { - string strError = ""; - - //if (string.IsNullOrEmpty(strText) == true) - //{ - // strError = "尚未输入文本"; - // goto ERROR1; - //} - - SetTextString(this.webBrowser1, ""); - - List records = new List(); - - for (int i = 0; i < 10; i++) - { - MessageRecord record = new MessageRecord(); - record.groups = strGroupName.Split(new char[] { ',' }); - record.creator = ""; // 服务器会自己填写 - record.data = "["+i.ToString()+"]"; - record.format = "text"; - record.type = "message"; - record.thread = ""; - record.expireTime = new DateTime(0); // 表示永远不失效 - records.Add(record); - } - - EnableControls(false); - try - { - // CancellationToken cancel_token = new CancellationToken(); - - try - { - MessageConnection connection = await this._channels.GetConnectionAsync( - this.textBox_config_messageServerUrl.Text, - ""); - SetMessageRequest param = new SetMessageRequest("create", - "", - records); - - SetMessageResult result = await connection.SetMessageAsync(param); - - this.Invoke(new Action(() => - { - SetTextString(this.webBrowser1, ToString(result)); - })); - } - catch (AggregateException ex) - { - strError = MessageConnection.GetExceptionText(ex); - goto ERROR1; - } - catch (Exception ex) - { - strError = ex.Message; - goto ERROR1; - } - return; - } - finally - { - EnableControls(true); - } - ERROR1: - this.Invoke((Action)(() => MessageBox.Show(this, strError))); - } - - static string ToString(MessageResult result) - { - StringBuilder text = new StringBuilder(); - text.Append("ResultValue=" + result.Value + "\r\n"); - text.Append("ErrorInfo=" + result.ErrorInfo + "\r\n"); - text.Append("String=" + result.String + "\r\n"); - return text.ToString(); - } - public void ShowMsg(MessageRecord record) - { - this.textBox1.Text += record.id + "\n"; - } - static void SetTextString(WebBrowser webBrowser, string strText) - { - SetHtmlString(webBrowser, "
" + HttpUtility.HtmlEncode(strText) + "
"); - } - - public static void SetHtmlString(WebBrowser webBrowser, -string strHtml) - { - webBrowser.DocumentText = strHtml; - } - - void EnableControls(bool bEnable) - { - //if (this.InvokeRequired) - //{ - // this.Invoke(new Action(EnableControls), bEnable); - // return; - //} - //this.Enabled = bEnable; - } - - private void Form1_Load(object sender, EventArgs e) - { - - } } } diff --git a/TestMessage/TestMessage.csproj b/TestMessage/TestMessage.csproj index ad07379c..cfb972d7 100644 --- a/TestMessage/TestMessage.csproj +++ b/TestMessage/TestMessage.csproj @@ -51,7 +51,6 @@ Form1.cs - diff --git a/TestMessage/myMsgHandler.cs b/TestMessage/myMsgHandler.cs deleted file mode 100644 index 318b7698..00000000 --- a/TestMessage/myMsgHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -using DigitalPlatform.Message; -using dp2Message; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestMessage -{ - public class myMsgHandler:BaseMsgHandler - { - public Form1 form = null; - - - public override int InternalDoMessage(MessageRecord record, out string strError) - { - strError = ""; - form.ShowMsg(record); - - return 1; - } - } -} diff --git a/dp2Message/BaseMsgHandler.cs b/dp2Message/BaseMsgHandler.cs index 81703bfa..c46b9f1a 100644 --- a/dp2Message/BaseMsgHandler.cs +++ b/dp2Message/BaseMsgHandler.cs @@ -52,29 +52,22 @@ public void Init(MessageConnectionCollection channels, this._wxMsgThread.BeginThread(); } - - int _inGetMessage = 0; // 防止因为 ConnectionStateChange 事件导致重入 void _channels_ConnectionStateChange(object sender, ConnectionEventArgs e) { - if (_inGetMessage > 0) - return; - if (e.Action == "Reconnected" || e.Action == "Connected") { - FillDeltaMessage(); + this._wxMsgThread.Activate(); + //this._wxMsgThread.Worker(); } } void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Resume) - FillDeltaMessage(); - } - - void FillDeltaMessage() - { - Task.Factory.StartNew(() => DoLoadMessage()); + { + this._wxMsgThread.Activate(); + } } /// @@ -96,98 +89,89 @@ void _channels_AddMessage(object sender, AddMessageEventArgs e) } // 被1分钟轮循一次的工作线程调用 - public async void DoLoadMessage() + public void DoLoadMessage() { - if (_inGetMessage > 0) - return; - _inGetMessage++; + string strGroupName = "_patronNotify";//""; + string strError = ""; try { - string strGroupName = "_patronNotify";//""; - string strError = ""; - try - { - MessageConnection connection = await this._channels.GetConnectionAsync( - this._dp2mserverUrl, - ""); - /* + MessageConnection connection = this._channels.GetConnectionAsync( + this._dp2mserverUrl, + "").Result; + /* 我提前说一下:小批循环获取,如果按照一个条件,不在中途删除服务器端的消息,应该是这样循环:start=0,count=100; start=101,count=100,... 如果你每次中途都主动删除(或者失效)刚处理的这小批消息,循环就是这样了:start=0,count=100; start=0,count=100;... 明白么?分号位置是要做删除调用的 当然如果请求的条件发生变化了,就不算同一批了 多次调用只是为了避免突破内存空间问题,脑子里要清楚这个原则。 - */ - int batchNo = 1;//用于输出,看结果对不对 - long totalCount = -1;//用于输出,看结果对不对 -1表示未赋值 - - int start = 0; - int count = 10; - REDO: - CancellationToken cancel_token = new CancellationToken(); - string id = Guid.NewGuid().ToString(); - GetMessageRequest request = new GetMessageRequest(id, - "", - strGroupName, // "" 表示默认群组 - "", - "", - start, - count); - - // 改为同步小批循环获取。原来回调函数方案删除或失效有问题,也占响应时间 - GetMessageResult result = connection.GetMessage(request, - new TimeSpan(0, 1, 0), - cancel_token); - if (result.Value == -1) - { - goto ERROR1; - } - if (result.Value == 0) - { - goto END1; - } - - // 用于测试,第一次返回的记为总记录数 - if (totalCount == -1) - totalCount = result.Value; - - // 做事,发送消息给微信,里面用了expire,所以下次的start位置不变 - if (result.Results != null && result.Results.Count > 0) - { - this.DoMessage(result.Results, "getMessage"); - } - - // 继续获取消息 - if (result.Results != null && result.Results.Count > 0 - && result.Value > result.Results.Count) - { - //start += result.Results.Count; + */ + int batchNo = 1;//用于输出,看结果对不对 + long totalCount = -1;//用于输出,看结果对不对 -1表示未赋值 + + int start = 0; + int count = 10; + REDO: + CancellationToken cancel_token = new CancellationToken(); + string id = Guid.NewGuid().ToString(); + GetMessageRequest request = new GetMessageRequest(id, + "", + strGroupName, // "" 表示默认群组 + "", + "", + start, + count); + + // 改为同步小批循环获取。原来回调函数方案删除或失效有问题,也占响应时间 + GetMessageResult result = connection.GetMessage(request, + new TimeSpan(0, 1, 0), + cancel_token); + if (result.Value == -1) + { + goto ERROR1; + } + if (result.Value == 0) + { + goto END1; + } - batchNo++; //用于输出,测试 - goto REDO; - } + // 用于测试,第一次返回的记为总记录数 + if (totalCount == -1) + totalCount = result.Value; - END1: - // 输出一次分批获取的情况 - this.WriteErrorLog("总记录数[" + totalCount + "],分为[" + batchNo + "]批获取完:)"); - } - catch (AggregateException ex) + // 做事,发送消息给微信,里面用了expire,所以下次的start位置不变 + if (result.Results != null && result.Results.Count > 0) { - strError = MessageConnection.GetExceptionText(ex); - goto ERROR1; + this.DoMessage(result.Results, "getMessage"); } - catch (Exception ex) + + // 继续获取消息 + if (result.Results != null && result.Results.Count > 0 + && result.Value > result.Results.Count) { - strError = ex.Message; - goto ERROR1; + //start += result.Results.Count; + + batchNo++; //用于输出,测试 + goto REDO; } - return; - ERROR1: - this.WriteErrorLog(strError); + END1: + // 输出一次分批获取的情况 + this.WriteErrorLog("总记录数[" + totalCount + "],分为[" + batchNo + "]批获取完:)"); + } + catch (AggregateException ex) + { + strError = MessageConnection.GetExceptionText(ex); + goto ERROR1; } - finally + catch (Exception ex) { - _inGetMessage--; + strError = ex.Message; + goto ERROR1; } + return; + + ERROR1: + this.WriteErrorLog(strError); + } void OutputMessage(long totalCount, @@ -241,67 +225,72 @@ private bool AddMsgToHashTable(string msgId) /// private void DoMessage(IList records, string from) { - lock (msgLocker) + + //lock (msgLocker) + //{ + try { - try + if (records == null || records.Count == 0) + return; + + List delIds = new List(); + foreach (MessageRecord record in records) { - if (records == null || records.Count == 0) - return; + // 先检查一下是不是_patronNotify组消息,因为addMessage会得到账户配置的所有组的消息,getMessage没关系只获取_patronNotify群消息 + bool bPatronNotifyGroup = this.CheckIsNotifyGroup(record.groups); + if (bPatronNotifyGroup == false) + { + continue; + } - List delIds = new List(); - foreach (MessageRecord record in records) + // getMessage与addMessage处理消息都会走到这里,对这段代码加锁,以保证不会重发消息。 + + this.WriteErrorLog("这次是[" + from + "]传过来的消息。"); + + // 从已处理消息队列里查重,如果是前面处理过的,则不再处理 + bool bSended = this.checkMsgIsDone(record.id); + if (bSended == true) { - // 先检查一下是不是_patronNotify组消息,因为addMessage会得到账户配置的所有组的消息,getMessage没关系只获取_patronNotify群消息 - bool bPatronNotifyGroup = this.CheckIsNotifyGroup(record.groups); - if (bPatronNotifyGroup == false) - { - continue; - } - - // getMessage与addMessage处理消息都会走到这里,对这段代码加锁,以保证不会重发消息。 - - this.WriteErrorLog("这次是[" + from + "]传过来的消息。"); - - // 从已处理消息队列里查重,如果是前面处理过的,则不再处理 - bool bSended = this.checkMsgIsDone(record.id); - if (bSended == true) - continue; - - string strError = ""; - /// - /// -1 不符合条件,不处理 - /// 0 未绑定微信id,未处理 - /// 1 成功 - /// - int nRet = this.InternalDoMessage(record, out strError); - if (nRet == -1) - { - this.WriteErrorLog("[" + record.id + "]出错:" + strError); - // todo,对于这些消息是否删除?,现在是统统删除 - } - - // 加到已处理消息队列里 - this.AddMsgToHashTable(record.id); - - - // 加到删除列表 - delIds.Add(record.id); + this.WriteErrorLog("["+ record.id+"]在hashtable里已存在。"); + continue; } - //删除处理过的消息 - if (delIds.Count > 0) + string strError = ""; + /// + /// -1 不符合条件,不处理 + /// 0 未绑定微信id,未处理 + /// 1 成功 + /// + int nRet = this.InternalDoMessage(record, out strError); + if (nRet == -1) { - string strError = ""; - int nRet = this.DeleteMessage(delIds, out strError); - if (nRet == -1) - throw new Exception(strError); + this.WriteErrorLog("[" + record.id + "]出错:" + strError); + // todo,对于这些消息是否删除?,现在是统统删除 } + + // 加到已处理消息队列里 + this.AddMsgToHashTable(record.id); + + + // 加到删除列表 + delIds.Add(record.id); } - catch (Exception ex) + + //删除处理过的消息 + if (delIds.Count > 0) { - this.WriteErrorLog(ex.Message); + string strError = ""; + int nRet = this.DeleteMessage(delIds, out strError); + if (nRet == -1) + throw new Exception(strError); } } + catch (Exception ex) + { + this.WriteErrorLog(ex.Message); + } + //} + } @@ -317,8 +306,8 @@ private void DoMessage(IList records, string from) /// public virtual int InternalDoMessage(MessageRecord record, out string strError) { - strError = ""; - return 1; + strError = "未处理"; + return -1; } /// /// 检查是否属于通知组的消息 @@ -363,7 +352,7 @@ int DeleteMessage(List idList, out string strError) } SetMessageRequest param = new SetMessageRequest("expire", //delete - "", + "dontNotifyMe", records); try