在上节中,我们已经初步对 SignalR 进行了了解,这一节我们将做一个SignalR Demon,具体的步骤如下:
1. 创建一个 mvc 4 web 应用程序,并选择 Basic
2. 创建一个 Home 控制器, 创建好后,目录应该是这样的:
3. 在项目中,鼠标右键打开 Nuget 程序管理包,在 Nuget 程序管理包中 输入 signalr 这样的字符串进行搜索,在搜索结果中选中 Microsoft ASP.NET SignalR 这个项目,并点击安装
4. 在刚创建好的 Home 控制器 添加 一个 Index 的 Action ,并创建视图,视图的完整代码如下:
<body>
<div class="container">
<input type="text" id="message" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
</div>
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="signalr/hubs"> </script>
<script type="text/javascript">
$(function () {
// 定义一个代理, 以引用 Hub
var chat = $.connection.chatHub;
//定义client端的javascript function,供server端hub,通过dynamic的方式,调用所有Clients的javascript function
// 在对话框中输入聊天者的姓名.
$('#displayname').val(prompt('Enter your name:', ''));
// 创建一个函数,以使 Hub 可以广播消息。
chat.client.broadcastMessage = function (name, message) {
// 对字符串进行html 编码
var encodedName = $('#displayname').text(name).html();
var encodedMsg = $('#message').text(message).html();
//在页面中追加并显示聊天信息
$('#discussion').append('•' + encodedName + ': ' + encodedMsg + '' + '</br>');
};
// 设置消息框的焦点格式.
$('#message').focus();
// 与服务器建立连接
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// 在Hub中调用 Send 方法
chat.server.send($('#displayname').val(), $('#message').val());
// 清空消息输入框
$('#message').val('').focus();
});
});
});
</script>
</body>
5. 在项目中创建 OWin Startup 启动类, 并在Configuration(IAppBuilder app) 中添加以下 代码:app.MapHubs();
这段代码的意义就是将 应用程序映射到 Hub 中去,这是在程序启动运行时就会执行的。
6. 添加 ChatHub.cs 类,并创建 send(string name, string message) 方法,以便在客户端能调用
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
7. 对项目进行编译,如果没有错的话,程序执行的结果应该是这样的(以下是用fire fox浏览器):
在用IE 调试时,在项目中我们可以看到自动生成的一些调用脚本,其中 hubs.js 就是个我们在客户端所引用的 <script src="signalr/hubs"> </script>,它将会把服务器中的方法推送到客户端,以便在客户端可以调用
Hubs.js 的完整代码如下:
/*!
* ASP.NET SignalR JavaScript Library v2.1.2
* http://signalr.net/
*
* Copyright Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the Apache 2.0
* https://github.com/SignalR/SignalR/blob/master/LICENSE.md
*
*/
/// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
/// <reference path="jquery.signalR.js" />
(function ($, window, undefined) {
/// <param name="$" type="jQuery" />
"use strict";
if (typeof ($.signalR) !== "function") {
throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");
}
var signalR = $.signalR;
function makeProxyCallback(hub, callback) {
return function () {
// Call the client hub method
callback.apply(hub, $.makeArray(arguments));
};
}
function registerHubProxies(instance, shouldSubscribe) {
var key, hub, memberKey, memberValue, subscriptionMethod;
for (key in instance) {
if (instance.hasOwnProperty(key)) {
hub = instance[key];
if (!(hub.hubName)) {
// Not a client hub
continue;
}
if (shouldSubscribe) {
// We want to subscribe to the hub events
subscriptionMethod = hub.on;
} else {
// We want to unsubscribe from the hub events
subscriptionMethod = hub.off;
}
// Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
for (memberKey in hub.client) {
if (hub.client.hasOwnProperty(memberKey)) {
memberValue = hub.client[memberKey];
if (!$.isFunction(memberValue)) {
// Not a client hub function
continue;
}
subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
}
}
}
}
}
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs();
}).disconnected(function () {
// Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
// (instance, shouldSubscribe)
registerHubProxies(proxies, false);
});
proxies['chatHub'] = this.createHubProxy('chatHub');
proxies['chatHub'].client = { };
proxies['chatHub'].server = {
send: function (name, message) {
return proxies['chatHub'].invoke.apply(proxies['chatHub'], $.merge(["Send"], $.makeArray(arguments)));
}
};
return proxies;
};
signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());
}(window.jQuery, window));
好了,非常感谢你的阅读,如果有什么好的想法,欢迎与我交流。
源码下载地址:下载源码