ASP.NET SignalR

何为ASP.NET SignalR,有什么用

ASP.NET SignalR是一个ASP.NET库,是为了实现实时web通信而创造的,能让服务器与客户端实现即时通信,而不需要服务器等待接收到客户端请求才能返回内容。简言之,就是可以实现服务端主动给客户端发送请求。

ASP.NET SignalR的依赖环境

  • Windows 7&8 或 Windows Server 2008 R2 & Windows 2012
  • IIS 8 + & 集成模式
  • .NET FRAMEWOKR 4.5 +
  • 支持websocket的浏览器

实际上,ASP.NET SignalR请求是基于http的,在不支持websocket的环境下,会自动降级到Comet模式(即Forever Frame/Ajax long polling)兼容旧版本客户端

ASP.NET SignalR的两种通信模型

1、Persistent connection 持久性连接

Persistent Connections表示一个发送单个,编组,广播信息的简单终结点。开发人员通过使用持久性连接Api,直接访问SignalR公开的底层通信协议

2、Hub 集线器

Hubs是基于连接Api的更高级别的通信管道,它允许客户端和服务器上彼此直接调用方法,SignalR能够很神奇地处理跨机器的调度,使得客户端和服务器端能够轻松调用在对方端上的方法。使用Hub还允许开发人员将强类型的参数传递给方法并绑定模型

 

讲了那么多废话,下面就演示两种不同通信模型的实例吧

 

准备条件

1、使用Visual Studio 2015,创建一个默认的ASP.NET MVC项目

2、安装ASP.NET SignalR,在nuget power shell中执行

Install-Package Microsoft.AspNet.SignalR

3、添加SignalR服务,添加->新建项->Visual C#/Web/SignalR,便可看到两种不同的通信模型

4、在根目录下面新建Connections文件夹

Persistent Connections演示实例

1、在Connections文件下,添加->新建项->Visual C#/Web/SignalR,选择SignalR永久连接类(v2)

 

    public class ChatConnection : PersistentConnection
    {
        protected override Task OnConnected(IRequest request, string connectionId)
        {
            return Connection.Send(connectionId, "Welcome!");
        }

        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            return Connection.Broadcast(data);
        }
    }

 

2、在根目录下找到Startup.cs

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR<ChatConnection>("/Connections/ChatConnection");
        }
    }

 

3、在HomeController.cs

        public ActionResult PersistentConnection()
        {
            return View();
        }

 

4、新建PersistentConnection.cshtml

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>PersistentConnection</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
    <script type="text/javascript">
        $(function () {

            // 声明PersistentConnection连接
            var connection = $.connection("/Connections/ChatConnection");

            $('#displayname').val(prompt('Enter your name:', ''));
            $("msg").focus();

            // 接收内容
            connection.received(function (data) {
                $('#messages').append('<li>' + data + '</li>');
            });

            // 开启连接
            connection.start().done(function () {
                $("#broadcast").click(function () {
                    
                    // 发送内容
                    connection.send($('#displayname').val() + '' + $('#msg').val());
                });
            });

        });
    </script>
</head>
<body>
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="broadcast" />
    <input type="hidden" id="displayname" />
    <ul id="messages"></ul>
</body>
</html>

 

5、在Chrome中运行

 

 

 

 

 

 

 

 

Hubs演示实例(图片就不贴了,基本与Persistent Connections一样)

1、在Connections文件下,添加->新建项->Visual C#/Web/SignalR,选择SignalR集线器类(v2)

    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // 回调客户端函数,这里与客户端
            Clients.All.broadcastMessage(name, message);
        }
    }

 

2、在根目录下找到Startup.cs

        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }

 

3、在HomeController.cs

        public ActionResult Hub()
        {
            return View();
        }

 

4、并新建Hub.cshtml

 

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Hub</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    <!-- 引用jquery库 -->
    <script src="/Scripts/jquery-1.10.2.min.js"></script>
    <!-- 引用SignalR库 -->
    <script src="/Scripts/jquery.signalR-2.2.1.min.js"></script>
    <!-- 声明自动生成hub脚本路径 -->
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {
            // 声明hub代理,首字母需小写,与hub类名对应(也可使用别名)
            var chat = $.connection.chatHub;

            // 服务端回调函数,与hub类中Clients.All.broadcastMessage(name, message)对应
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };

            $('#displayname').val(prompt('Enter your name:', ''));
            $('#message').focus();

            // 开启hub连接
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {

                    // 发送内容至hub服务端,与public void Send(string name, string message)对应
                    chat.server.send($('#displayname').val(), $('#message').val());

                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>

 

5、运行

 

 

 

 

到此,ASP.NET SignalR介绍完毕

 

posted @ 2016-09-01 12:07  simoje  阅读(3093)  评论(3编辑  收藏  举报