欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

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

发布时间:2017-01-07 14:53  回复:0  查看:2456   最后回复:2017-01-07 14:53  

本文和大家分享的主要是基于ajaxmsmq技术消息推送功能相关实现方法,一起来看看吧,希望对大家学习ajax 有所帮助。

  我设计的这个推送demo是基于ajax长轮询+msmq消息队列来实现的,具体交互过程如下图:

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

先说说这个ajax长轮询,多长时间才算长呢?这个还真不好界定。

  这里是相对普通ajax请求来说的,通常处理一个请求也就是毫秒级别的时间。但是这里的长轮询方式

  在ajax发送请求给服务器之后,服务器给调用端返回数据的时间多长那可还真不好说。嘿嘿,这关键要看

  我们啥时候往msmq队列中推送数据了,先看看推送的效果图吧。。。。。

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


抱歉,没弄张动态效果图给大家。实现的功能大体上就是这样。上图中的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 = "推送状态";

  }

  }

  }

  消息推送Winform程序代码

  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 TaskGetMessage()

  {

  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();

  }

  }

  }

  Web服务端代码

  @{

  ViewBag.Title = "Push";

  }

  <h2>Pushh2>

  <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 + "

· 

" + data + "

· 

· 

");

· 

  getMessage();

  });

  }script>

  页面视图代码

  当然,在这个只是一个初级的消息推送demo,是否能胜任生产环境的需要还有待考证。

 

来源:博客园



您还未登录,请先登录

热门帖子

最新帖子