创建自托管的SignalR服务端

2023-05-11,,

微软官方例子地址:http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host

1、说明:

    SignalR服务端可以使Asp.net程序,也就可以是控制台或服务程序这种不需要再IIS上托管的程序。这就是本篇文章的内容介绍。

2、安装扩展:

    使用Nuget控制台:Install-Package Microsoft.AspNet.SignalR.SelfHost自托管服务端所需要的程序集。 

            Install-Package Microsoft.Owin.Cors跨域访问所需,SignalR服务端与客户端不在同一域上。

3、新建(控制台项目):

    ①新建Startup类,第一句为跨域所要设置的

app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();

    ②新建Hub类,定义Send推送方法,在此方法中会调用客户端定义的方法。

public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}

    ③在main方法中启动SignalR服务端

string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}

4、新建(Web项目):    

      在此项目中,将使用到上一步中得到的SignalR服务端来向客户端推送数据。

      注意几点:

          ①此时的hub地址为上一步定义好的url地址。

<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>

          ②要连接的Hub地址要与上一步中保持一致,hub类名在这里使用时注意首字母小写。

$.connection.hub.url = "http://localhost:8080/signalr";
 $(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8080/signalr"; // Declare a proxy to reference the hub.
var chat = $.connection.myHub; // Create a function that the hub can call to broadcast messages.
chat.client.addMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});

5、生成之后,先启动SignalR服务端。

    

    

创建自托管的SignalR服务端的相关教程结束。

《创建自托管的SignalR服务端.doc》

下载本文的Word格式文档,以方便收藏与打印。