ASP.NET Signalr 2.0 實現一個簡單的聊天室


  學習了一下SignalR 2.0,http://www.asp.net/signalr 文章寫的很詳細,如果頭疼英文,還可以機翻成中文,雖然不是很准確,大概還是容易看明白。

理論要結合實踐,自己動手做了個簡單的聊天室。

   

開發環境:Win7 + Visual Studio 2012

主要步驟:

  • 添加SignalR庫到你的ASP.NET web 應用.
  • 建立一個Hub類推送內容到客戶端.
  • 建立一個 OWIN Startup 類來配置應用.
  • 使用SignalR jQuery庫發送和顯示信息.

打開vs2012,新建項目ASP.NET MVC4 Web 應用程序(選擇.NET Framework 4.5),名稱為MyChat

  

下一步選擇 Internet 應用程序模板

  

項目建立完成后在解決方案資源管理器中,項目名稱上點右鍵菜單中選擇 管理Nuget 程序包... 打開對話框,選擇聯機 搜索 SignalR

返回搜索結果后 找到並下載,如果沒有問題,就會安裝SignalR庫到你的項目,如果安裝過程出現錯誤,可能是依賴項不符合要求。

需要跨域訪問,需要同樣方法下載 Microsoft.Owin.Cors 到項目

在解決方案資源管理器 新建文件夾 Hubs ,在這個文件夾上右鍵菜單 添加一個類文件 ChatHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

namespace MyChat.Hubs
{
    public class ChatHub : Hub
    {
        private static Dictionary<string,string> _clients = new Dictionary<string,string>(); //保存在線用戶列表
        public Task OnConnected() //暫時無用
        {
            return base.OnConnected();
        }

        public void Send(string name, string message) //處理發送信息
        {
            _clients[Context.ConnectionId] = name;
            Clients.All.addNewMessageToPage(name, message); //廣播消息給所有連接到此Hub的客戶端,addNewMessageToPage 是客戶端定義的
        }

        public void List() //獲取在線用戶列表
        {
            List<string> list = new List<string>();
            foreach (var k in _clients)
            {
                list.Add(k.Value);
            }
            Clients.Caller.listAll(list);//只發送給調用者, listAll 也是客戶端定義的
        }
    }
}

要運行起來還需要一個啟動文件,在項目根目錄添加一個類文件 Startup.cs ,SignalR 依賴於Owin,需要這個文件,否則會報錯

using Owin;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
[assembly: OwinStartup(typeof(MyChat.Startup))]
namespace MyChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.UseCors(CorsOptions.AllowAll); //跨域支持
            app.MapSignalR(); //路由映射
        } 
    }
}

服務端就寫好了,下面開始客戶端。在Controller 文件夾右鍵,添加一個控制器 ChatController, 並給Index 方法添加一個視圖

代碼如下

@{
    ViewBag.Title = "聊天";
}
<h2>聊天</h2>
<div class="container">
    <br />
    <div>在線:<span id="clientlist">&nbsp;</span></div>
    <div style="height:200px;margin-top:20px; padding:10px; border:solid 1px #ccc; overflow:auto;">
    <ul id="discussion">
    </ul>
    </div>
    <div>昵稱: <input type="text" id="displayname" style="width:100px;" /> &nbsp;信息: <input type="text" id="message" style="width:200px;" />
    &nbsp;<input type="button" id="sendmessage" value="發送" /> <input type="button" id="getclients" value="獲取列表" /></div>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.--> 
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub; //客戶端代理,
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + htmlEncode(name) 
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            }; //服務器端會調用
            chat.client.listAll = function (list) {
                var html = '';
                for (i = 0; i < list.length; i++) {
                    html += list[i] + '&nbsp;';
                }
                $('#clientlist').html(html);
            }; //服務器端會調用
            // Get the user name and store it to prepend to messages.
            //$('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    var dispname = $('#displayname').val();
                    var message = $('#message').val();
                    if (dispname == '') {
                        alert('請輸入昵稱');
                        return false;
                    }
                    if (message == '') {
                        alert('請輸入信息');
                        return false;
                    }
                    // Call the Send method on the hub. 
                    chat.server.send(dispname, message );
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
                $('#getclients').click(function () {
                    chat.server.list();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

$.connection.chatHub 是個客戶端代理,定義在 ~/signalr/hubs 腳本文件中,火狐瀏覽器,查看源碼,可以看到這個文件的源碼。

為了方便,我們可以在布局文件中加個菜單

<li>@Html.ActionLink("聊天", "Index", "Chat")</li>

至此,簡單的聊天室完成了,點擊運行,就可以在瀏覽器中查看效果,多開幾個窗口,就可以互相聊天了。
代碼下載 http://pan.baidu.com/s/1ePme7 (百度網盤 30M)

有時間實踐一下SignalR的分組,就可以實現一對一聊天,多聊天室功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM