栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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


Push

接收消息列表





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

如果你也有更好的实现和建议,都欢迎留言给我。

源码在这里:http://pan.baidu.com/s/1hsHSLTy

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/91555.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号