切换风格

默认晚霞 雪山 粉色心情 伦敦 花卉 绿野仙踪 加州 白云 星空 薰衣草 城市 简约黑色 简约米色 龙珠
回复 0
     紫钻仅向指定用户开放  

394

主题

411

帖子

5万

积分

管理员

论坛BOSS

Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15

积分
51995

最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献优秀版主荣誉管理论坛元老

SignalR实现服务器端推送消息到客户端[复制链接]
发表于 2018-12-9 22:31:32 | 显示全部楼层 |阅读模式

目前是游客浏览,请注册

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
使用SignalR可实现服务器端主动向客户端推送消息,只需要在NuGet里下载引用即可

SignalR实现服务器端推送消息到客户端

SignalR实现服务器端推送消息到客户端

[HTML] 纯文本查看 复制代码
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta charset="utf-8" />
    <title>聊天室</title>
    <script src="~/Scripts/jquery-1.6.4.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.0.js"></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 != "") {
                        feed.invoke("sendOne", toUserId, $("#message").val())
                        .done(function () {
                            //alert("发送成功!");
                            $("#message").val("").focus();
                        })
                        .fail(function (e) {
                            alert(e);
                            $("#message").focus();
                        });
                    }
                    else {
                        feed.invoke("send", $("#message").val())
                        .done(function () {
                            //alert("发送成功!");
                            $("#message").val("").focus();
                        })
                        .fail(function (e) {
                            alert(e);
                            $("#message").focus();
                        });
                    }
                });

            });

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

            feed.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);
            });

            feed.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>



[C#] 纯文本查看 复制代码
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 Test.Models
{
    [HubName("feed")]
    public class FeedHub : 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);
        }
    }
}


[C#] 纯文本查看 复制代码
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

[assembly: OwinStartup(typeof(Test.Models.Startup))]
namespace Test.Models
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}


[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.ClientName = "聊客-" + Guid.NewGuid().ToString("N");
            var onLineUserList = FeedHub.OnLineUsers.Select(u => new SelectListItem() { Text = u.Value, Value = u.Key }).ToList();
            onLineUserList.Insert(0, new SelectListItem() { Text = "-所有人-", Value = "" });
            ViewBag.OnLineUsers = onLineUserList;
            return View();
        }
    }
}


示例代码来源网络

上一篇:C#类库查询手册
下一篇:ASP.NET的HttpContext.Current.Server.MapPath获取不到

打赏列表

~~~还没有人打赏~~~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|五秒论坛 ( 鄂ICP备18019426号 )|申请友情链接

返回顶部