使用 ASP.NET SignalR实现实时通讯

27 篇文章 0 订阅
15 篇文章 0 订阅

ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程。实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务器代码可以立即向其推送内容,而不是让服务器等待客户端请求新的数据。

  官网:http://signalr.net/

  下载:install-package Microsoft.AspNet.SignalR

  

 

  本节将简单快速介绍

 

实现原理

  1. 如果浏览器<=Internet Explorer 8,用长轮询的方式
  2. 如果配置中指定了使用jsonp,则会使用长轮询的方式
  3. 如何需要创建跨域连接,将会如使用WebSocket,如果一下条件满足的话(否则用长轮询)
    1. 客户端支持WebSocket
    2. 服务端支持WebSocket
    3. 客户端支持Cross-Origin Resource Sharing

 

基于SignalR(SR)的实现原理,所以SR在客户端浏览器IE8以上基本都是完全兼容的。可以说完全支持jQuery 1.6.4的浏览器就能支持SignalR。

 

Hello World

创建空的Asp.Net项目

 

安装

  install-package Microsoft.AspNet.SignalR

  install-package bootstrap

 

添加一个集线器类

复制代码
public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }
}
复制代码

 

添加一个OWIN Startup类

复制代码
[assembly: OwinStartup(typeof(SignalRChart.Startup))]
 
namespace SignalRChart
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}
复制代码

 

添加一个index.html

1.导入js

复制代码
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
复制代码

 

2.hub

复制代码
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
 
// Call the Send method on the hub.
chat.server.send(name, message);
 
 // Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
}
复制代码

 

快速分析

Hub代码

 

Client代码

 

 

 

1.发送给所有客户端
Clients.All.onMsg

2.发送给单一客户端
Clients.Client(_clientID).onMsg 

3.发送给其他客户端
Clients.AllExcept(_clientID).onMsg
Clients.Ohther.onMsg

4.发送给当前客户端
Clients.Caller.onMsg

 

 

注意事项

In ASP.NET MVC 4 you can do the following:

<script src="~/signalr/hubs"></script>

If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:

<script src="@Url.Content("~/signalr/hubs")"></script>

Chat.cshtml頁面代碼:

@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <div id="discussion" style="overflow: auto; width: 400px; height: 200px; border: 1px solid #999; ">
    </div>
</div>


@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                var div = document.getElementById('discussion');
                div.innerHTML = div.innerHTML + '<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</li>';
                div.scrollTop = div.scrollHeight;
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laizhixue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值