顯示具有 SignalR 標籤的文章。 顯示所有文章
顯示具有 SignalR 標籤的文章。 顯示所有文章

2014年4月5日 星期六

SignalR2.0 實作聊天室上線清單

繼上一篇聊天室做好之後,再來加一下聊天清單

http://tsengpm.blogspot.tw/2014/04/mvc4-signalr-chat-signalr-20.html

其實就是改一下ChatHub.cs這個檔案

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

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public static ConcurrentDictionary<string, UserData> UserList = new ConcurrentDictionary<string, UserData>();

        //離開時刪除ID
        public override Task OnDisconnected()
        {
            UserData Value;
            UserList.TryRemove(Context.ConnectionId, out Value);

            return Clients.All.showConnected(UserList);
        }
        public void GetUsers()
        {
            Clients.All.showConnected(UserList);
        }
        //進入時加入ID
        public void Join(UserData data)
        {
            data.Connected = DateTime.Now.ToString("f");
            UserList.TryAdd(Context.ConnectionId, data);
            Clients.All.showConnected(UserList);
        }
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }   
    }
    public class UserData
    {
        public int Sid { get; set; }
        public string Connected { get; set; }
        public string Name { get; set; }

    }
}

另外在頁面上的start也要調整

$.connection.hub.start().done(function () {
 $('#sendmessage').click(function () {
  
  chat.server.join({ Sid: $('#displayId').val(), Name: $('#displayName').val() }).done(function () {
   chat.server.getUsers();
  });
 });
});

接著在頁面上放一個userList的 ul控制項,然後Key入以下的程式碼,他就會一直append了

chat.client.showConnected = function (userList) {
            $.each(userList, function (index, data) {               
                $("#userList").append("<li>" + data.Name + "</li>");
            });
        };

2014年4月4日 星期五

使用 MVC4 開發 SignalR Chat - SignalR 2.0

之前練習了用SignalR來做聊天室,都成功了,今天造著步驟做,居然失敗了, 查了一下,之前的版本好像是1.3 ,現在SignalR升級到2.0了,寫法有一些改變,真是XXX... 會出現錯誤這樣的錯誤訊息

'System.Web.Routing.SignalRRouteExtensions.MapHubs(System.Web.Routing.RouteCollection)' 已過時: 'Use IAppBuilder.MapSignalR in an Owin Startup class. See http://go.microsoft.com/fwlink/?LinkId=320578 for more details.' 


1. 先把SignalR移除掉,然後陸續安裝以下幾個package

PM> Uninstall-Package Microsoft.AspNet.SignalR –RemoveDependencies

PM> Install-Package Microsoft.AspNet.SignalR

PM> Install-Package Microsoft.AspNet.SignalR -Version 2.0.1

PM> Install-Package Microsoft.Owin

但是我居然在Console底下一直建立失敗,只好用 介面來新增


接著可以看到已經加入了這些參考



Scripts中也有了2.0.3的版本





為了確認SignalR能正確載入,之前會在global.asax加入RouteTable.Routes.MapHubs();
現在改變寫法了,先新增一個SignalR的資料夾,然後在裡面新增一個ChatHub.cs的類別




using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }
    }
}





接著再新增一個Startup.cs的類別


using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}





接著在HTML碼裡面Key入以下的程式碼

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion">
        </ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js" ></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    <!--Add script to update the page and send messages.--> 
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub. 
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message. 
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // 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 () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>

這邊一樣會出現SignalR錯誤的問題,所以按照上一篇的方式修改就可以了

在 BundleConfig.cs 中,加入 SignalR.js的 script, 另外因為IE解析 json 格式的問題,也要多加入 json2.js

bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
            "~/Scripts/json2.js", 
            "~/Scripts/jquery.signalR-{version}.js"));

當然在 ~/Script 資料夾中,也要放入一個 json2.js 的檔案 可以在這邊取得: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

另外在HTML中,修改一下 SignalR.js include的方式

 @Scripts.Render("~/bundles/signalR")

接著就可以跑了

2013年9月8日 星期日

使用 MVC4 開發 SignalR Chat

參考文章:http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc-4

1. 新增一個MVC4的專案

2.  選「網際網路應用程式」

3.  在「套件管理主控台」,安裝SingalR

4. 輸入  install-package Microsoft.AspNet.SignalR

5.  之後檢查script底下,應該有SignalR的相關Script

6. 接下來新增一個Hubs的資料夾




7.  新增一個 SignalR Hub Class
 


8.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(name, message);
        }
    }
}
9. 在 Global.asax 裡加入這一行

RouteTable.Routes.MapHubs();
 

10. 在「 Controllers/HomeController.cs」中新增一個 Chat 的 method
1
2
3
4
public ActionResult Chat()
{
    return View();
}

11. 在View >> Home 底下新增一個 Chat 的 View


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@{
    ViewBag.Title = "Chat";
}

<h2>Chat</h2>

<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</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-1.0.1.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>');
            };
            // 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 () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
12. 重點來了,按 F5 跑起來後,居然出現 執行階段錯誤: SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/hubs.



13.Google了好久,終於解決了

14.  在 BundleConfig.cs 中,加入 SignalR.js的 script, 另外因為IE解析 json 格式的問題,也要多加入 json2.js



















1
2
3
bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
            "~/Scripts/json2.js", 
            "~/Scripts/jquery.signalR-{version}.js"));
15.  當然在 ~/Script 資料夾中,也要放入一個 json2.js 的檔案
可以在這邊取得: https://github.com/douglascrockford/JSON-js/blob/master/json2.js


16. 另外在 View/Home/Chat.cshtml中,修改一下 SignalR.js include的方式


1
@Scripts.Render("~/bundles/signalR")


17. 在按 F5執行一次,http://localhost:xxxx/home/chat,終於成功了