周末在家搗鼓了一下消息推送的簡單例子,其實也沒什么技術含量,歡迎大伙拍磚。
我設計的這個推送demo是基于ajax長輪詢+msmq消息隊列來實現的,具體交互過程如下圖:
先說說這個ajax長輪詢,多長時間才算長呢?這個還真不好界定。
這里是相對普通ajax請求來說的,通常處理一個請求也就是毫秒級別的時間。但是這里的長輪詢方式
在ajax發送請求給服務器之后,服務器給調用端返回數據的時間多長那可還真不好說。嘿嘿,這關鍵要看
我們啥時候往msmq隊列中推送數據了,先看看推送的效果圖吧。。。。。
抱歉,沒弄張動態效果圖給大家。實現的功能大體上就是這樣。上圖中的winform程序中我們點擊即刻發送按鈕,同時網頁上我們就能看到新推送的數據。
好了,說完具體實現流程和效果之后馬上就開始編碼實現吧。。。。
消息推送Winform程序代碼
namespace SenderApp{ public partial class Form1 : Form { private string queueName = @"./Private$/pushQueue"; private MessageQueue pushQueue = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { var queue = this.GetQueue(); if (string.IsNullOrEmpty(this.textBox1.Text)) { this.label1.Text = "推送消息不能為空"; return; } queue.Send(this.textBox1.Text, "messagePush"); this.label1.Text = "消息推送成功"; } catch (Exception ex) { this.label1.Text = string.Format("消息推送失敗:{0}",ex.Message); } } private MessageQueue GetQueue() { if (this.pushQueue == null) { if (!MessageQueue.Exists(queueName)) { this.pushQueue = MessageQueue.Create(queueName); } else { this.pushQueue = new MessageQueue(queueName); } } return this.pushQueue; } private void textBox1_MouseDown(object sender, MouseEventArgs e) { this.textBox1.Text = ""; this.label1.Text = "推送狀態"; } }}
Web服務端代碼
namespace MessagePushWeb.Controllers{ public class HomeController : Controller { private static string queueName = @"./Private$/pushQueue"; private static MessageQueue pushQueue = null; public ActionResult Index() { return View(); } public async Task<ActionResult> GetMessage() { string msg = await Task.Run(() => { return this.ReadMessage(); }); return Content(msg); } private MessageQueue GetQueue() { if (pushQueue == null) { if (MessageQueue.Exists(queueName)) { pushQueue = new MessageQueue(queueName); pushQueue.Formatter = new XmlMessageFormatter(new string[] { "System.String" }); } } return pushQueue; } private string ReadMessage() { var queue = GetQueue(); Message message = queue.Receive(); return message.Body.ToString(); } }}
頁面視圖代碼
@{ ViewBag.Title = "Push";}<h2>Push</h2><div>接收消息列表</div><div id="msg"></div><script type="text/javascript"> $(function () { getMessage(); }); function getMessage() { $.get("/home/getmessage", {}, function (data) { var _msg = $("#msg").html(); $("#msg").html(_msg + "<li>" + data + "</li>"); getMessage(); }); }</script>
當然,在這個只是一個初級的消息推送demo,是否能勝任生產環境的需要還有待考證。
如果你也有更好的實現和建議,都歡迎留言給我。
源碼在這里:http://pan.baidu.com/s/1hsHSLTy
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答