瞬間讓SignalR 實如今線聊天室~

ASP.NET SignalR 是爲 ASP.NET 開發人員提供的一個庫,能夠簡化開發人員將實時 Web 功能添加到應用程序的過程。實時 Web 功能是指這樣一種功能:當所鏈接的客戶端變得可用時服務器代碼能夠當即向其推送內容,而不是讓服務器等待客戶端請求新的數據。javascript

直接看效果圖:java

實現過程以下:jquery

新建一個Hub服務器

完整代碼:app

Startupide

using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Net.Ulon.SignalR.Startup))]
namespace Net.Ulon.SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

HubCSui

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.AspNet.SignalR.Hubs;
namespace Net.Ulon.SignalR.Hub
{
    /// <summary>
    /// HubName不填寫即爲類名稱
    /// </summary>
    [HubName("Chat")]
    public class ChatHub : Microsoft.AspNet.SignalR.Hub
    {
        /// <summary>
        /// 獲取當前客戶端ID
        /// </summary>
        public string _clientID { get { return Context.ConnectionId; } }
        /// <summary>
        /// 獲取當前時間
        /// </summary>
        private string _now { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"); } }
        /// <summary>
        /// 獲取消息
        /// </summary>
        private string GetMsg(string msg)
        {
            return string.Format("{0} : {1}", _now, msg);
        }
        /// <summary>
        /// 獲取喊話
        /// </summary>
        private string GetSay(string say)
        {
            return string.Format("{0} :【{1}】 {2}", _now, _clientID, say);
        }
        public void Send(string msg)
        {
            //發送消息給其餘客戶端
            Clients.All.onMsg(_clientID, this.GetSay(msg));
            //發送消息給當前客戶端
            Clients.Caller.onMsg(_clientID, this.GetMsg("消息發送成功~"));
            //Clients.Client(_clientID).onMsg(id, "Client Connect");
        }
        /// <summary>
        /// 鏈接
        /// </summary>
        /// <returns></returns>
        public override Task OnConnected()
        {
            Clients.Caller.onMsg(_clientID, this.GetMsg("鏈接服務器~"));
            Clients.AllExcept(_clientID).onMsg(_clientID, this.GetSay("閃耀登場~"));
            return base.OnConnected();
        }
        /// <summary>
        /// 斷開
        /// </summary>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            Clients.Caller.onMsg(_clientID, this.GetMsg("鏈接斷開~"));
            Clients.AllExcept(_clientID).onMsg(_clientID, this.GetSay("瀟灑離去~"));
            return base.OnDisconnected(stopCalled);
        }
        /// <summary>
        /// 從新鏈接
        /// </summary>
        /// <returns></returns>
        public override Task OnReconnected()
        {
            Clients.Caller.onMsg(_clientID, this.GetMsg("從新鏈接服務器~"));
            Clients.AllExcept(_clientID).onMsg(_clientID, this.GetSay("重出江湖~"));
            return base.OnReconnected();
        }
    }
}  

ViewHtmlthis

@{
    ViewBag.Title = "Home Page";
}
@section scripts{
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var chat = $.connection.Chat;
            registerClientMethods(chat);
            $.connection.hub.start().done(function () {
                registerEvents(chat);
            });
            //註冊客戶端事件
            function registerEvents(chat) {
                $("#send").click(function () {
                    chat.server.send($("#msg").val());
                });
            }
            //註冊客戶端方法
            function registerClientMethods(chat) {
                chat.client.onMsg = function (id, text) {
                    $("#record").append("<div>" + text + "</div>");
                }
            }
        });
    </script>
}
<div>hello world~</div>
<div>
    <input type="text" id="msg" />
    <br />
    <input type="button" id="send" value="發送消息" />
</div>
<div id="record"></div>  
 
主要的功能就是  服務端推送消息/ 客戶端發送消息
 
服務端推送消息
onMsg 是自定義的消息方法(客戶端JS):
             chat.client.onMsg = function (id, text) {
                    $("#record").append("<div>" + text + "</div>");
                }
1.發送給全部客戶端
Clients.All.onMsg
 
2.發送給單一客戶端
Clients.Client(_clientID).onMsg  
 
3.發送給其餘客戶端
Clients.AllExcept(_clientID).onMsg
Clients.Ohther.onMsg
 
4.發送給當前客戶端
Clients.Caller.onMsg
 
除了上面的單一的還有 GroupUser
 
客戶端發送消息
                $("#send").click(function () {
                    chat.server.send($("#msg").val());
                });
 
客戶端發送下到服務端就是經過調用server,其中send是服務端定義的方法:
 
        public void Send(string msg)
        {
            //發送消息給其餘客戶端
            Clients.All.onMsg(_clientID, this.GetSay(msg));
 
            //發送消息給當前客戶端
            Clients.Caller.onMsg(_clientID, this.GetMsg("消息發送成功~"));
            //Clients.Client(_clientID).onMsg(id, "Client Connect");
        }  
相關文章
相關標籤/搜索