SignalR 实现 Web 客户端与服务器实时通信

来源:互联网 发布:bot的知识图谱数据api 编辑:程序博客网 时间:2024/06/05 01:10

SignalR 实现 Web 客户端与服务器实时通信

### 简介 ###
ASP .NET SignalR 是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信。什么是实时通信的Web呢?就是让客户端(Web页面)和服务器端可以互相实时通知消息及调用方法。

WebSockets是HTML5提供的新的API,可以在Web网页与服务器端间建立Socket连接,当WebSockets可用时(即浏览器支持Html5)SignalR使用WebSockets,当不支持时SignalR将使用其它技术来保证达到相同效果。

SignalR当然也提供了非常简单易用的高阶API,使服务器端可以单个或批量调用客户端上的JavaScript函数,并且非常 方便地进行连接管理,例如客户端连接到服务器端,或断开连接,客户端分组,以及客户端授权,使用SignalR都非常 容易实现。

### 基于 SignalR 实现在线聊天室

为了展示 SignalR 的强大之处, 这里就直接写一个在线聊天室的案例。

首先创建一个 Web Application, 命名为 SignalRQuickStart, 打开 工具--Nuget程序包管理器--程序包管理器控制台, 键入 Install-Package Microsoft.AspNet.SignalR 来安装 SignalR, 我这里还安装了 BootStrap 以用来美化界面。 安装 BootStrap : Install-Package BootStrap, 好了, 这样准备工作就做好了。 还是老样子, 将解释以注释的方式写下吧。

下面新建集线器 Hub:

using Microsoft.AspNet.SignalR;namespace SignalRQuickStart{    public class RealTimeHub : Hub    {        /// <summary>        /// 向所有客户端广播信息        /// </summary>        /// <param name="ip">ip 地址</param>        /// <param name="name">用户昵称</param>        /// <param name="content">消息内容</param>        public void SendMsg(string ip, string name, string content)         {            //调用客户端 Script 脚本            Clients.All.broadcastMsg(ip, name, content);        }    }}

新建OWIN Startup:

using Microsoft.Owin;using Owin;[assembly: OwinStartup(typeof(SignalRQuickStart.Startup))]namespace SignalRQuickStart{    public class Startup    {        public void Configuration(IAppBuilder app)        {            //将所有 SignalR 集线器映射至 /signalr 传输管道            app.MapSignalR();        }    }}

新建一般处理文件IpAddressHandler.ashx 以获取客户端 Ip:

using System.Web;namespace SignalRQuickStart{    /// <summary>    /// IpAddressHandler 的摘要说明    /// </summary>    public class IpAddressHandler : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            context.Response.Write(context.Request.UserHostAddress);        }        public bool IsReusable        {            get            {                return false;            }        }    }}

新建 Default.html 页面:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title>基于 SignalR 打造的在线聊天室</title>    <link href="Content/bootstrap.min.css" rel="stylesheet" /></head><body>    <h3 class="text-center">基于 SignalR 打造的在线聊天室</h3>    <div class="container">        <div class="row">            <form class="form-horizontal">                <div class="form-group-sm">                    <label class="col-sm-1">ip:</label>                    <div class="col-sm-11">                        <input type="text" name="ip" id="ip" class="form-control" value="" readonly="readonly" />                    </div>                </div>                <div class="form-group-sm">&nbsp;</div>                <div class="form-group-sm">                    <label class="col-sm-1">昵称:</label>                    <div class="col-sm-11">                        <input type="text" name="name" id="name" class="form-control" value="" placeholder="请输入昵称...(长度不大于10个字符)" />                    </div>                </div>                <div class="form-group-sm">&nbsp;</div>                <div class="form-group-sm">                    <label class="col-sm-1">消息:</label>                    <div class="col-sm-11">                        <textarea id="msg" rows="3" class="form-control" placeholder="请输入消息内容..."></textarea>                    </div>                </div>                <div class="form-group-sm">&nbsp;</div>                <div class="form-group-sm">                    <label class="col-sm-1"></label>                    <div class="col-sm-11">                        <a href="#" id="sendMsg" class="btn btn-primary pull-right">发送</a>                    </div>                </div>            </form>        </div>        <div class="row">&nbsp;</div>        <div class="row">            <ul class="col-sm-12 list-group" id="msgContent">                <li class="hidden"></li>            </ul>        </div>    </div>    <script src="Scripts/jquery-1.9.1.min.js"></script>    <script src="Scripts/jquery.signalR-2.2.0.min.js"></script>    <script src="/signalr/hubs"></script>    <script type="text/javascript">        function getIp(callback) {            console.log('function getIp has been called');            $.post('IpAddressHandler.ashx')            .success(callback)            .fail(function () {                console.log('获取客户端ip地址失败!');            });        };        function initIp() {            getIp(function (result) {                if (!result)                    result = '0.0.0.0';                $('#ip').val(result);            });        }        $(function () {            initIp();            var realTimeHub = $.connection.realTimeHub;            //实现服务器调用的 broadcastMsg 方法            realTimeHub.client.broadcastMsg = function (ip, name, msg) {                var msgModel = $('<li>').addClass('list-group-item').html('[' + ip + ']<strong>' + name + '</strong>:<br />' + msg);                console.log(msgModel);                msgModel.insertBefore($('#msgContent').children('li').first());            };            $('#sendMsg').click(function () {                if ($('#name').val().trim() == '' || $('#name').val().trim().length > 10) {                    alert('昵称不合法!');                    return;                }                //调用服务器申明的 sendMsg() 方法                $.connection.hub.start().done(function () {                    getIp(function (result) {                        if (!result)                            result = '0.0.0.0';                        $('#ip').val(result);                        realTimeHub.server.sendMsg(result, $('#name').val(), $('#msg').val());                    });                });            });        });    </script></body></html>

案例源码会在评论中给出。 (由于网速太差, 所以就没有上传展示图片了, 后续可能会补上)

1 0
原创粉丝点击