[英]how to access signalr hub in azure webrole
I have a working SignalR Hub that contains some continuous running methods, they are managing sessions lifecycle, connecting sessions ... these continuous running methods are executed every X seconds using the Timer
class. 我有一个工作正常的SignalR集线器,其中包含一些连续运行的方法,它们正在管理会话生命周期,连接会话...这些连续运行的方法使用
Timer
类每隔X秒执行一次。 this is really not a good practice because of thread leaking, performance issues, locks ... 由于线程泄漏,性能问题,锁,这实际上不是一个好习惯。
A better implementation would be to have a WebRole, and all those "worker methods" should go in the WebRole.cs
file, witch makes a lot of sense, since this is the very purpose of roles in azure. 更好的实现方法是拥有一个WebRole,所有这些“工人方法”都应放在
WebRole.cs
文件中,巫婆很有道理,因为这是天蓝色角色的真正目的。
The probleme now, it can not get a working instance of the hub context using this code : 现在的问题是,使用以下代码无法获取中心上下文的工作实例:
var hubContext = GlobalHost.ConnectionManager.GetHubContext<AppHub>();
hubContext.Clients.All.Message("hello from webrole");
hubContext
is instantiated (so not null) but even so, still nothing is broadcasted to clients. hubContext
被实例化(因此不能为null),但是即使如此,仍然没有任何内容广播到客户端。 No errors and no exceptions ! 没有错误也没有例外!
I guess this is happening because the WebRole.cs
and Startup.cs
are instantiated in different threads ? 我猜这是因为
WebRole.cs
和Startup.cs
是在不同的线程中实例化的?
How can I access hub context in the WebRole.cs
? 如何在
WebRole.cs
访问中心上下文?
Thank you. 谢谢。
hubContext
is instantiated (so not null) but even so, still nothing is broadcasted to clients.hubContext
被实例化(因此不能为null),但是即使如此,仍然没有任何内容广播到客户端。 No errors and no exceptions !没有错误也没有例外!
I can reproduce same issue on my side. 我可以在自己的身边重现同样的问题。 To broadcast the message to clients from
WebRole.cs
, you can try to install Microsoft.AspNet.SignalR.Client and invoke hub method to send message to clients. 要从
WebRole.cs
向客户端广播消息,您可以尝试安装Microsoft.AspNet.SignalR.Client并调用集线器方法以将消息发送给客户端。 The following code works for me in the Compute Emulator, you can refer to it. 以下代码在Compute Emulator中对我有用,您可以参考它。
WebRole.cs WebRole.cs
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// For information on handling configuration changes
// see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.
return base.OnStart();
}
public override void Run()
{
while (true)
{
System.Threading.Thread.Sleep(30000);
var hub = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:57276/signalr/hubs");
var proxy = hub.CreateHubProxy("ChatHub");
hub.Start().Wait();
//invoke hub method
proxy.Invoke("mySend", "hello from webrole; " + DateTime.UtcNow.ToString());
}
}
}
ChatHub.cs ChatHub.cs
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
public void mySend(string message)
{
Clients.All.addNewMessageToPage("webrole", message);
}
}
Test result 测试结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.