zoukankan      html  css  js  c++  java
  • SignalR实时通信

    /// <summary>
    /// Message集线器类
    /// </summary>
    [HubName("chathub")]
    public class ChatHub : Hub
    {
        private Broadcaster _broadcaster;
        public ChatHub()
            : this(Broadcaster.Instance)
        {
        }
        public ChatHub(Broadcaster broadcaster)
        {
            _broadcaster = broadcaster;
        }
        /// <summary>
        /// 给所有页面发送消息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="message"></param>
        public void Send(string name, string message)
        {
            _broadcaster.broadcastMessage(name, message);
        }
        /// <summary>
        /// 给指定页面发送消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        public void Send(int id, string message)
        {
            _broadcaster.broadcastMessage(id, message);
        }
        [HubMethodName("connect")]
        public void Connect(string id)
        {
            var connnectId = Context.ConnectionId;//Value
            if (id != null && connnectId != null)
            {
                SERedisHelper.StringSet(id, connnectId, 10);
            }
        }
    }
    
    public class Broadcaster
    {
        private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(() => new Broadcaster());
        private readonly IHubContext _hubContext;
        public Broadcaster()
        {
            _hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        }
        public static Broadcaster Instance
        {
            get
            {
                return _instance.Value;
            }
        }
        /// <summary>
        /// 给所有页面发送消息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="message"></param>
        public void broadcastMessage(string name, string message)
        {
            _hubContext.Clients.All.broadcastMessage(name, message);
        }
        /// <summary>
        /// 给指定页面发送消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        public void broadcastMessage(int id, string message)
        {
            string strValue = SERedisHelper.StringGet(id.ToString());
            BIT.Common.Log.Debug("C# 后台 向客户端 发送消息的方法strValue:" + strValue);
            if (strValue != null && strValue.Length > 0)
                _hubContext.Clients.Client(strValue).broadcastMessage(message);
        }
    }
    ChatHub.cs内部代码
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            #region Redis配置
            //添加redis  / /任何连接或集线器连接和配置应该去这里
            // Redis Server 地址 是正在运行的服务器的名称
            string ServerString = "";
            if (System.Configuration.ConfigurationManager.AppSettings["RedisServerString"] != null)
            {
                ServerString = System.Configuration.ConfigurationManager.AppSettings["RedisServerString"].ToString();
            }
            int port = 0; // 端口
            if (System.Configuration.ConfigurationManager.AppSettings["RedisServerPort"] != null)
            {
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["RedisServerPort"].ToString(), out port);
            }
            //是你的在 Redis中定义 定义配置的 密码。
            string password = "";
            if (System.Configuration.ConfigurationManager.AppSettings["RedisServerPassword"] != null)
            {
                password = System.Configuration.ConfigurationManager.AppSettings["RedisServerPassword"].ToString();
            }
            // SignalR创建一个 Redis,pub / sub通道具有该名称。
            string appname = "";
            if (System.Configuration.ConfigurationManager.AppSettings["RedisServerAppName"] != null)
            {
                appname = System.Configuration.ConfigurationManager.AppSettings["RedisServerAppName"].ToString();
            }
            RedisScaleoutConfiguration redisScaleoutConfiguration = new RedisScaleoutConfiguration(ServerString, port, password, appname);
            //连接DB,默认为0
            redisScaleoutConfiguration.Database = 3;
            //SignalR用Redis
            GlobalHost.DependencyResolver.UseRedis(redisScaleoutConfiguration);
            #endregion
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();//启动SignalR
        }
    }
    Startup.cs内部代码-使用redis
    <appSettings>
      <!--Redis配置-->
      <add key="RedisServerString" value="localhost" />
      <add key="RedisServerPort" value="6379" />
      <add key="RedisServerPassword" value="" />
      <add key="RedisServerAppName" value="chathub" />
    </appSettings>
    Web.config配置
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </div>
            
        </form>
    </body>
    </html>
    发送消息的页面HTML结构
    protected void Button1_Click(object sender, EventArgs e)
    {
        Broadcaster.Instance.broadcastMessage(1, "msg");
    }
    发送消息页面的后台代码
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div id="sss">
        
        </div>
            <asp:HiddenField ID="hfID" runat="server" value="1"/>
        </form>
        <script src="../Scripts/jquery-1.6.4.min.js"></script>
        <script src="../Scripts/jquery.signalR-2.2.1.min.js"></script>
        <script src="../signalr/hubs"></script>
        <script type="text/javascript">
            var i = 0;
            $(function () {
                $("#sss").html(i);
                var chat = $.connection.chathub;
                chat.client.broadcastMessage = function (message) {
                    i++;
                    $("#sss").html(i);
                };
    
    
                //日志输出,以备调试使用
                $.connection.hub.logging = true;
    
                var id = $("#hfID").val();
                $.connection.hub.start(function () {
                    chat.invoke("connect", id);
                });
            });
        </script>
    </body>
    </html>
    接收消息的页面代码

  • 相关阅读:
    设计模式之——工厂模式
    设计模式之——单例模式
    jQuery 全选 正反选
    将本地jar包添加到maven中
    配置项目启动的时候就加载 servlet
    Cannot call sendError() after the response has been committed(filter问题)
    mybatis pagehelper实现分页
    防止表单重复提交
    java.lang.Exception: No runnable methods 解决方案
    js 倒计时跳转页面
  • 原文地址:https://www.cnblogs.com/zhyue93/p/signalr_1.html
Copyright © 2011-2022 走看看