您的位置:首页 > 编程语言

基于ajax与msmq技术的消息推送功能实现代码

2016-12-26 09:07 756 查看

周末在家捣鼓了一下消息推送的简单例子,其实也没什么技术含量,欢迎大伙拍砖。

我设计的这个推送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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息