Win*_*Guy 4 c# signalr signalr-hub signalr.client
我有一个Web窗体应用程序和测试,以查看SignalR如何满足我的要求.我的中心代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRTest.Hubs
{
public class NotificationHub : Hub
{
public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();
public NotificationHub()
{
var myInfo = Context.QueryString["myInfo"];
_Timer.Interval = 2000;
_Timer.Elapsed += TimerElapsed;
_Timer.Start();
}
void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Random rnd = new Random();
int i = rnd.Next(0, 2);
var hub = GlobalHost.ConnectionManager.GetHubContext("NotificationHub");
hub.Clients.All.Alert(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的客户电话:
<script type="text/javascript">
$(function () {
var logger = $.connection.notificationHub;
logger.client.Alert = function (msg) {
if (msg == 1) {
$("#HyperLink1").show();
$("#HyperLink2").hide();
}
else {
$("#HyperLink1").hide();
$("#HyperLink2").show();
}
};
$.connection.hub.qs = "myInfo=12345";
$.connection.hub.start();
});
</script>
Run Code Online (Sandbox Code Playgroud)
但是,由于某种原因,当检查服务器代码上的Context(在hub中)时,它为null,因此我无法检索查询字符串值.有任何想法吗?
我不相信在创建Hub时可以使用Context.相反,您可以覆盖OnConnectionHub类:
public override Task OnConnected()
{
var myInfo = Context.QueryString["myInfo"];
return base.OnConnected();
}
Run Code Online (Sandbox Code Playgroud)
Hub对象生命周期的文档:
您没有实例化Hub类或从服务器上自己的代码调用其方法; 所有这些都由SignalR Hubs管道完成.每次需要处理Hub操作时,SignalR都会创建Hub类的新实例,例如客户端连接,断开连接或对服务器进行方法调用时.
因为Hub类的实例是瞬态的,所以不能使用它们来维护从一个方法调用到下一个方法的状态.每次服务器从客户端接收方法调用时,Hub类的新实例都会处理该消息.要通过多个连接和方法调用来维护状态,请使用其他方法,例如数据库,Hub类上的静态变量,或不从Hub派生的其他类.如果将数据保留在内存中,使用Hub类上的静态变量等方法,则应用程序域回收时数据将丢失.