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

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

理論要結合實踐,本身動手作了個簡單的聊天室。jquery

   

開發環境:Win7 + Visual Studio 2012web

主要步驟:跨域

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

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

  

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

  

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

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

須要跨域訪問,須要一樣方法下載 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的分組,就能夠實現一對一聊天,多聊天室功能

相關文章
相關標籤/搜索