• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Asp.Net下SignalR的三种实现方式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

第一种:采用集线器类(Hub)+非自动生成代理模式:

              服务端与客户端分别定义的相对应的方法,客户端通过代理对象调用服务端的方法,服务端通过IHubConnectionContext回调客户端的方法,客户端通过回调方法接收结果。

服务端代码:

//StartUp.cs  采用OWIN启动方式
using System;

using System.Threading.Tasks;

using Microsoft.Owin;

using Owin;

using Microsoft.AspNet.SignalR;

 

[assembly: OwinStartup(typeof(TestWebApp.Models.Startup))]

 

namespace TestWebApp.Models

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            app.MapSignalR();

        }

    }

}

 

 

//ChatHub类文件

 

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Hubs;

using System;

using System.Collections.Concurrent;

using System.Collections.Generic;

using System.Linq;

using System.Web;
namespace TestWebApp.Models
{
    [HubName("chat")]
    public class ChatHub : Hub
    {
        public static ConcurrentDictionary<string, string> OnLineUsers = new ConcurrentDictionary<string, string>();

        [HubMethodName("send")]
        public void Send(string message)

        {
            string clientName = OnLineUsers[Context.ConnectionId];

            message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>");

            Clients.All.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), clientName, message);
        }

        [HubMethodName("sendOne")]
        public void Send(string toUserId, string message)
        {
            string clientName = OnLineUsers[Context.ConnectionId];

            message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>");

            Clients.Caller.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("您对 {1}", clientName, OnLineUsers[toUserId]), message);

            Clients.Client(toUserId).receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 对您", clientName), message);
        }

        public override System.Threading.Tasks.Task OnConnected()
        {
            string clientName = Context.QueryString["clientName"].ToString();

            OnLineUsers.AddOrUpdate(Context.ConnectionId, clientName, (key, value) => clientName);

            Clients.All.userChange(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 加入了。", clientName), OnLineUsers.ToArray());

            return base.OnConnected();
        }
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) { string clientName = Context.QueryString["clientName"].ToString(); Clients.All.userChange(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 离开了。", clientName), OnLineUsers.ToArray()); OnLineUsers.TryRemove(Context.ConnectionId, out clientName); return base.OnDisconnected(stopCalled); } } }

 

web端代码:

<!DOCTYPE html>
<html>
<head>

    <meta name="viewport" content="width=device-width" />

    <meta charset="utf-8" />

    <title>聊天室</title>

    <script src="~/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>

    <script src="~/Scripts/jquery.signalR-2.2.0.min.js" type="text/javascript"></script>

    <style type="text/css">

        #chatbox {

            width: 100%;

            height: 500px;

            border: 2px solid blue;

            padding: 5px;

            margin: 5px 0px;

            overflow-x: hidden;

            overflow-y: auto;

        }

        .linfo {

        }

        .rinfo {

            text-align: right;

        }

    </style>

    <script type="text/javascript">

        $(function () {
            var clientName = $("#clientname").val();

            var eChatBox = $("#chatbox");

            var eUsers = $("#users");
            var conn = $.hubConnection();

            conn.qs = { "clientName": clientName };

            conn.start().done(function () {

                $("#btnSend").click(function () {

                    var toUserId = eUsers.val();

                    if (toUserId != "") {

                        chat.invoke("sendOne", toUserId, $("#message").val())

                        .done(function () {

                            //alert("发送成功!");

                            $("#message").val("").focus();

                        })

                        .fail(function (e) {

                            alert(e);

                            $("#message").focus();

                        });

                    }

                    else {

                        chat.invoke("send", $("#message").val())

                        .done(function () {

                            //alert("发送成功!");

                            $("#message").val("").focus();

                        })

                        .fail(function (e) {

                            alert(e);

                            $("#message").focus();

                        });

                    }

                });
            });

            var chat = conn.createHubProxy("chat");

            chat.on("receiveMessage", function (dt, cn, msg) {

                var clsName = "linfo";

                if (cn == clientName || cn.indexOf("您对") >= 0) clsName = "rinfo";

                eChatBox.append("<p class='" + clsName + "'>" + dt + " <strong>" + cn + "</strong> 说:<br/>" + msg + "</p>");

                eChatBox.scrollTop(eChatBox[0].scrollHeight);

            });
chat.on(
"userChange", function (dt, msg, users) { eChatBox.append("<p>" + dt + " " + msg + "</p>"); eUsers.find("option[value!='']").remove(); for (var i = 0; i < users.length; i++) { if (users[i].Value == clientName) continue; eUsers.append("<option value='" + users[i].Key + "'>" + users[i].Value + "</option>") } }); }); </script> </head> <body> <h3>大众聊天室</h3> <div id="chatbox"> </div> <div> <span>聊天名称:</span> @Html.TextBox("clientname", ViewBag.ClientName as string, new { @readonly = "readonly", style = "width:300px;" }) <span>聊天对象:</span> @Html.DropDownList("users", ViewBag.OnLineUsers as IEnumerable<SelectListItem>) </div> <div> @Html.TextArea("message", new { rows = 5, style = "width:500px;" }) <input type="button" value="发送消息" id="btnSend" /> </div> </body> </html>

备注:服务端与客户端代码都比较简单,网上相关的说明也有,这里就不再解说了,只说一下这种方式JS端调用服务端方法采用:chat.invoke,而被服务端回调的方法则采用:chat.on (这里的chat是createHubProxy创建得来的)

第二种:采用集线器类(Hub)+自动生成代理模式

服务端代码:与第一种相同,无需改变。

web端代码:

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <meta charset="utf-8" />

    <title>聊天室</title>

    <script src="~/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>

    <script src="~/Scripts/jquery.signalR-2.2.0.min.js" type="text/javascript"></script>

    <script src="~/signalr/hubs" type="text/javascript"></script>

    <style type="text/css">

        #chatbox {

            width: 100%;

            height: 500px;

            border: 2px solid blue;

            padding: 5px;

            margin: 5px 0px;

            overflow-x: hidden;

            overflow-y: auto;

        }

        .linfo {

        }


        .rinfo {

            text-align: right;

        }

    </style>

    <script type="text/javascript">

        $(function () {

            var clientName = $("#clientname").val();

            var eChatBox = $("#chatbox");

            var eUsers = $("#users");

            var chat = $.connection.chat;

            $.connection.hub.qs = { "clientName": clientName };

            chat.state.test = "test";

            chat.client.receiveMessage = function (dt, cn, msg) {

                var clsName = "linfo";

                if (cn == clientName || cn.indexOf("您对")>=0) clsName = "rinfo";

                eChatBox.append("<p class='" + clsName + "'>" + dt + " <strong>" + cn + "</strong> 说:<br/>" + msg + "</p>");

                eChatBox.scrollTop(eChatBox[0].scrollHeight);

            }

            chat.client.userChange = function (dt, msg, users) {

                eChatBox.append("<p>" + dt + " " + msg + "</p>");

                eUsers.find("option[value!='']").remove();

                for (var i = 0; i < users.length; i++
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Asp.net项目路径获取方法发布时间:2022-07-10
下一篇:
[翻译]ASP.NETMVCTip#3–在单元测试时提供明确的视图名字发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap