基於SignalR的web端即時通訊 - ChatJS


先看下效果。

ChatJS 是基於SignalR實現的Web端IM,界面風格模仿的是“臉書”,可以很方便的集成到已有的產品中。

項目官網:http://chatjs.net/

github地址:https://github.com/andrerpena/ChatJS

在瀏覽器端,ChatJS是一系列的jQuery插件,這些代碼都是使用TypeScript(微軟開發的JS的一個面向對象超集,可以編譯成JS)編寫。在服務端,是一個簡單的類庫。如果要集成ChatJS ,服務端需要做的僅僅是實現 IChatHub接口。同時,源碼中作者也給出了一個瀏覽器端和服務端的完整實現。 

運行作者提供的Demo

1,確保安裝 了VS2013,以及SqlServer2008或更新的版本。這是作者提的要求,但是我用VS2012也能打開且運行的很好。

2,下載代碼:https://github.com/andrerpena/ChatJS

3,創建一個叫做ChatJS 的數據庫,並執行 代碼中的 DbScripts\script.sql 腳本創建數據庫。

4,VS打開解決方案,並修改web.config的EF數據庫連接字符串。

5,編譯后運行,用戶名和密碼都是“admin”。 

在Web項目中集成 ChatJS

1,添加 ChatJS的引用。在NuGet管理器中搜索“ChatJS”並安裝,或命令行安裝:Install-Package ChatJS

2,確保啟動了SignalR。

     如果沒有安裝SignalR,則首先需要使用NuGet安裝SignalR,然后在Web項目的根目錄中創建一個名為 Startup.cs的文件,輸入以下代碼: 

using ChatJs.Admin;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof (Startup))]
namespace ChatJs.Admin
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            this.ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}

然后,在需要使用ChatJS的頁面引入以下兩個JS腳本:

<script src="/Scripts/jquery.signalR-2.0.3.min.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>

以上兩個腳本都是SignalR所必須的,有關SignalR的更多使用說明可以參考:http://signalr.net/

3,在需要使用ChatJS 的地方引用以下兩個文件:

<script src="/ChatJS/js/jquery.chatjs.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/ChatJS/css/jquery.chatjs.css" />

4,創建一個叫ChatHub的類,並實現IChatHub接口。

5,初始化ChatJS

<script type="text/javascript">
    $(function() {
        $.chat({
            // your user information
            userId: 1, // this should be dynamic
            // text displayed when the other user is typing
            typingText: ' is typing...',
            // the title for the user's list window
            titleText: 'Chat',
            // text displayed when there's no other users in the room
            emptyRoomText: "There's no one around here. You can still open a session in another browser and chat with yourself :)",
            // the adapter you are using
            adapter: new SignalRAdapter()
        });
    });
</script>


免責聲明!

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



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