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

  • Post author:
  • Post category:java


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

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

878b74c1c4cc93e5d7bad5f6610b65cd.png

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

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

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

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

e82f7f87df1e61da2d635af7b3e06ee2.png

抱歉,没弄张动态效果图给大家。实现的功能大体上就是这样。上图中的winform程序中我们点击即刻发送按钮,同时网页上我们就能看到新推送的数据。

好了,说完具体实现流程和效果之后马上就开始编码实现吧。。。。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

namespaceSenderApp

{public partial classForm1 : Form

{private string queueName = @”.\Private$\pushQueue”;private MessageQueue pushQueue = null;publicForm1()

{

InitializeComponent();

}private void button1_Click(objectsender, 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);

}

}privateMessageQueue GetQueue()

{if (this.pushQueue == null)

{if (!MessageQueue.Exists(queueName))

{this.pushQueue =MessageQueue.Create(queueName);

}else{this.pushQueue = newMessageQueue(queueName);

}

}return this.pushQueue;

}private void textBox1_MouseDown(objectsender, MouseEventArgs e)

{this.textBox1.Text = “”;this.label1.Text = “推送状态”;

}

}

}

消息推送Winform程序代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

namespaceMessagePushWeb.Controllers

{public classHomeController : Controller

{private static string queueName = @”.\Private$\pushQueue”;private static MessageQueue pushQueue = null;publicActionResult Index()

{returnView();

}public async TaskGetMessage()

{string msg = await Task.Run(() =>{return this.ReadMessage();

});returnContent(msg);

}privateMessageQueue GetQueue()

{if (pushQueue == null)

{if(MessageQueue.Exists(queueName))

{

pushQueue= newMessageQueue(queueName);

pushQueue.Formatter= new XmlMessageFormatter(new string[] { “System.String”});

}

}returnpushQueue;

}private stringReadMessage()

{var queue =GetQueue();

Message message=queue.Receive();returnmessage.Body.ToString();

}

}

}

Web服务端代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

@{

ViewBag.Title = “Push”;

}

Push

接收消息列表



版权声明:本文为weixin_35916518原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。