Signalr信息推送

  前序

    距离上次写文章,差不多已经大半年了。感觉自己越来越懒了,即使有时候空闲下来了,也不想动。前面买了一系列的Python的书,基础的看了大概有四分之一,剩下的基本上还未动,晚上回去也只是吃饭看电影。最近发现头偶尔开始痛了,欢迎是颈椎出问题,这周准备去看看。希望大家也多注意自己的身体,有什么 不舒服的及时发现,及时治疗。好了,扯远了,今天无意之间看到了关于Signalr的一些资料和demo,顿时觉得十分有用,遂花了一点时间,参考博友的资料,自己动手做了一个,再次记录下来,希望能给需要的朋友提供点帮助,也给自己的知识库增加的养料。有错误的地方,还望大家批评指出

  Signalr简介

  ASP .NET SignalR 是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信。实时通信:让客户端(Web页面)和服务器端可以互相通知消息及调用方法,当然这是实时操作的。

   Signalr使用

   1.新建一个mvc项目。(这里我使用的是vs2015)  这里关于MVC的详细就不赘述了,直接上项目结构,包括页面、控制器等,可能2015以下的结构有所不同。

     

  2.选中项目,添加引用---管理NuGet包程序包,在弹出的对话框中,搜索Signalr,如图:

    

    点击安装,安装提示步骤一步一步的安装。

  3.代码

    a.首先在Startup中app.MapSignalR();注册SignalR管道。    

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalrPushInformation.Startup))]
namespace SignalrPushInformation
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}
View Code

  b.添加信息处理类,需要继承Hub,这里我统一放在Models文件中。数据存储由于个人原因,这个地方我直接使用了字典的方式,大家可以存到数据中。

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Collections;

namespace SignalrPushInformation.Models
{
    [HubName("PushMessage")]
    public class PushMessage : Hub
    {

        public void Init()
        {
        }

        public void Push(string title, string message)
        {
            this.InsertMsg(title, message);
            // 调用所有客户端的sendMessage方法
            Clients.All.sendMessage(title, message);
        }
        private void InsertMsg(string title, string message)
        {
            Message msg = new Message();
            msg.Title = title;
            msg.MsgContent = message;
            MsgQueue.Insert(msg);
        }
    }
}
View Code

    这里需要指出‘sendMessage’方法是自定义的方法,会在客户端的时候使用,参数与客户需要一致,名称随意。

  c.发送信息view

@{
    ViewBag.Title = "SendMessage";
}
<title>发送消息</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
        // 引用自动生成的集线器代理,这里的PushMessage,需要和信息处理类名称一致
        var chat = $.connection.PushMessage;
        // 定义服务器端调用的客户端sendMessage来显示新消息,sendMessage方法需要信息处理类中的方法一致,参数一致
        chat.client.sendMessage = function (title, message) {
            // 向页面发送接收的消息
            sendMsg();
        };
        // 集成器连接开始,
        $.connection.hub.start()
            .done(function () {
                // 服务连接完成,给发送按钮注册单击事件
                $('#sendmessage').click(function () {
                    // 调用服务器端集线器的Send方法,push方法需要信息处理类中的方法一致
                    chat.server.push($("#title").val(), $('#message').val());
                });
                sendMsg();
            })
            .fail(function () {
                console.log("Could not Connect!");
            });
    });

    function sendMsg() {
        var options = {
            url: '/Message/MsgCount',
            type: 'post',
            success: function (data) {
                $("#count").html(data.count);
            }
        };
        $.ajax(options);
    }
</script>


<h2>
    发送消息
</h2>
<div>
    <label>我的消息:</label>
    <span style=" color:red; font-size:30px;" id="count"></span></div>
<p>
    <div>
        标题:
        <input type="text" id="title" />
    </div>
    <br /><br />
    <div>
        内容:
        <textarea id="message" rows="4" cols="30"></textarea>
    </div>
    <br /><br />
    <div>
        <input type="button" id="sendmessage" value="发送" />
    </div>
</p>
View Code

  d.接收信息view

@{
    ViewBag.Title = "ReceiveMessage";
}

<title>接受消息</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
        // 引用自动生成的集线器代理
        var chat = $.connection.PushMessage;
        // 定义服务器端调用的客户端sendMessage来显示新消息,sendMessage方法需要信息处理类中的方法一致,参数一致
        chat.client.sendMessage = function (title, message) {
            // 向页面发送接收的消息
            MsgCount(false);
            $("#msgcontent").after("<div>标题:" + title + ",消息内容:" + message + "</div>");
        };
        // 集成器连接开始
        $.connection.hub.start().done(function () {
            MsgCount(true);
        }).fail(function () {
            console.log("Could not Connect!");
        });
    });
    function MsgCount(init) {
        var options = {
            url: '/Message/MsgCount',
            type: 'post',
            success: function (data) {
                if (data != null) {
                    $("#count").html(data.count);
                    console.log(data.msg);
                    if (init) {
                        $.each(data.msg, function (n, m) {
                            $("#msgcontent").append("<div>标题:" + m.Title + ",消息内容:" + m.MsgContent + "</div>");
                        });
                    }
                }
            }
        };
        $.ajax(options);
    }
</script>


<h2>
    接收消息
</h2>

<div>
    <label>我的消息:</label>
    <span style="color: red; font-size: 30px; margin-right:10px;" id="count"></span><br />
    <br />
    <div id="msgcontent"></div>
</div>
View Code

  f.控制器代码

using SignalrPushInformation.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SignalrPushInformation.Controllers
{
    public class MessageController : Controller
    {
        // GET: Message
        public ActionResult ReceiveMessage()
        {
            return View();
        }

        public ActionResult SendMessage()
        {
            MsgQueue.Insert(new Message()
            {
                MsgContent = "zcy",
                Title = "zcy"
            });
            return View();
        }
        [HttpPost]
        public JsonResult MsgCount()
        {
            return Json(new { count = MsgQueue.GetCount(), msg = MsgQueue.Dequeue() });
        }
    }
}
View Code

  好了,一切都OK了,只需要编译生成,执行就行。详细的解释已经全部在代码中了,这个地方就不详细的说明。

  留在最后

    从开通博客到现在,了了的几篇文章,发现自己真的是太懒了。有时感觉真的不善于表达,想写点什么,但是不知道怎么写。后续的想对Python写一个系列,加深对Python的理解。虽然前面完整的看过一次基础的教程,但是发现还是有很多不懂的地方,希望以博客的形成,能加深自己的理解,也想改掉自己懒的毛病,,希望能让博客来监督我吧。

    最后老规矩,源码!(密码:MT4E)

  

   

   

原文地址:https://www.cnblogs.com/zcy-xy/p/5607636.html