码迷,mamicode.com
首页 > Web开发 > 详细

Asp.net MVC4 + signalR 聊天室实现

时间:2015-06-13 11:23:35      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

之前介绍了ServiceBus + SignalR的聊天室设计:
http://blog.csdn.net/lan_liang/article/details/46480529


如果还没有Azure账号,可以先完成SignalR的实现,这个例子容易上手一些。

如果要了解Service Bus,可以参照这里:

https://azure.microsoft.com/en-gb/documentation/articles/service-bus-dotnet-how-to-use-queues/


这篇是介绍Service Bus queue(1个订阅者)的,看完了可以了解一下Service Bus Topic(多个订阅者),语法大同小异:

https://azure.microsoft.com/en-gb/documentation/articles/service-bus-dotnet-how-to-use-topics-subscriptions/




1. VIEW的代码:

@{
    ViewBag.Title = "Signal R test";
}
<h2>Messages</h2>
<div class="container">
    <ul id="messages"></ul>
</div>


<div>
    Name : <input type="text" class="name"/>
</div>


<div>
    <input type="text" class="msg"/> <input type="button" value="send" class="send-btn"/>
</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.2.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 proxy = $.connection.serverTimeHub;
            // Create a function that the hub can call back to display messages.
            proxy.client.broadcastMessage = function (name, message) {
                // Add the message to the page.
                $(‘#messages‘).append(‘<li>‘ + name+" says: " + ‘</li>‘);
                $(‘#messages‘).append(‘<li>‘ + htmlEncode(message) + ‘</li>‘);
            };


            $(".send-btn").click(function() {
                proxy.server.send($(".name").val(), $(".msg").val());
            });


            // Start the connection.
            $.connection.hub.start();
        });


        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $(‘<div />‘).text(value).html();
            return encodedValue;
        }
    </script>
}  




2. 创建Hubs文件夹,添加hub类:


public class ServerTimeHub : Hub
    {
        public void Send(string name, string msg)
        {
            Clients.All.broadcastMessage(name, msg);
        }

    }  




3. Startup.Auth(或Global) 中完成Map:


 app.MapSignalR();


Asp.net MVC4 + signalR 聊天室实现

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/46481003

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!