Asp.net MVC4 + signalR 聊天室实现

时间:2021-01-26 00:11:07
之前介绍了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();