标签:
在实践本示例之前,你需要已经:
1. 有Azure账号
2. 已经创建了Service bus
3. 有权限部署到Cloud
1. 创建Azure Cloud Service 项目
2. 选择1个WebRole
3. 创建一个Hubs文件夹和ChatHub.cs:
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message, Environment.MachineName, RoleEnvironment.CurrentRoleInstance.Id);
}
4. 安装所需要的nuget:
microsoft asp.net signalR
signalR service bus
5.打开Home/Index.cshtml
添加如下代码(注意你的jquery和signalR版本,做相应替换):
@{ Layout = null; } <html> <head> <link rel="shortcut icon" href="http://icons.iconarchive.com/icons/sora-meliae/matrilineare/96/Status-dialog-information-icon.png"> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.js"></script> <script src="/signalr/hubs"></script> </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 type="text/javascript"> $(function () { var newMsg = false; var window_focused = false; var chat = $.connection.chatHub; chat.client.broadcastMessage = function (name, message, machineName, instanceId) { newMsg = true; var encodedName = $(‘<div />‘).text(name).html(); var encodedMsg = $(‘<div />‘).text(message).html(); $(‘#discussion‘).append(‘<li><strong>‘ + encodedName + ‘</strong>: ‘ + encodedMsg ); }; var name = prompt(‘Enter your name:‘, ‘‘); $(‘#displayname‘).val(name); $("#discussion").append("<li><strong>" + name + " entered" + " room </strong></li>"); $(‘#message‘).focus(); $("#message").keydown(function(e) { if (e.keyCode === 13) { $(‘#sendmessage‘).click(); } }); function setTitle1() { if (newMsg === true) { document.title = "New Msg"; setTimeout(setTitle2, 500); } } function setTitle2() { if (newMsg === true) { document.title = ""; setTimeout(setTitle1, 500); } } setInterval(function() { if (window_focused === false) { setTitle1(); } }, 1000); $.connection.hub.start().done(function () { $(‘#sendmessage‘).click(function () { newMsg = false; chat.server.send($(‘#displayname‘).val(), $(‘#message‘).val()); $(‘#message‘).val(‘‘).focus(); }); }); $(window).focus(function (e) { newMsg = false; window_focused = true; }); }); </script> </body> </html>
<add key="ServiceBusConnectionString" value="Endpoint=sb://your string/;SharedAccessKeyName=your key;SharedAccessKey=your key" /></appSettings>
GlobalHost.DependencyResolver.UseServiceBus( CloudConfigurationManager.GetSetting("ServiceBusConnectionString"), "MyChat"); app.MapSignalR();
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/46480529