在Solution Explorer中,右击“Project”,然后选择Add | SignalR Hub Class (v2)。将类命名为ChatHub.cs,并确定。你将使用这个类作为服务端的 hub 来发送消息到所有的客户端。
将ChatHub类的代码替换如下:
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);
}
}
}
using Owin;
using Microsoft.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();
}
}
}
@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class=&#34;container&#34;>
<input type=&#34;text&#34; id=&#34;message&#34; />
<input type=&#34;button&#34; id=&#34;sendmessage&#34; value=&#34;Send&#34; />
<input type=&#34;hidden&#34; id=&#34;displayname&#34; />
<ul id=&#34;discussion&#34;>
</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=&#34;~/Scripts/jquery.signalR-2.1.0.min.js&#34;></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src=&#34;~/signalr/hubs&#34;></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.
$(&#39;#discussion&#39;).append(&#39;<li><strong>&#39; + htmlEncode(name)
+ &#39;</strong>: &#39; + htmlEncode(message) + &#39;</li>&#39;);
};
// Get the user name and store it to prepend to messages.
$(&#39;#displayname&#39;).val(prompt(&#39;Enter your name:&#39;, &#39;&#39;));
// Set initial focus to message input box.
$(&#39;#message&#39;).focus();
// Start the connection.
$.connection.hub.start().done(function () {
$(&#39;#sendmessage&#39;).click(function () {
// Call the Send method on the hub.
chat.server.send($(&#39;#displayname&#39;).val(), $(&#39;#message&#39;).val());
// Clear text box and reset focus for next comment.
$(&#39;#message&#39;).val(&#39;&#39;).focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $(&#39;<div />&#39;).text(value).html();
return encodedValue;
}
</script>
}