我正在尝试从控制器方法向我的客户端方法发送数据,该方法在实例客户端断开连接时返回响应。
控制器 目前..
public void SomeMethod(){
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
while(true){
hubContext.Clients.All.addNameValue(name,value);
}
}
我想要什么..
bool someProperty = false
public string SomeMethod(){
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
while(true & (someProperty == false)){
hubContext.Clients.All.addNameValue(name,value);
}
return "done";
}
因为我们知道客户端断开了集线器覆盖的方法..
集线器
public override Task OnDisconnected(bool stopCalled = true)
{
Console.WriteLine("Hub Disconnected: {0}\n", Context.ConnectionId);
return (base.OnDisconnected(stopCalled));
}
是否有任何方法可以从集线器外部跟踪控制器实例,以便可以完成这样的事情?
public override Task OnDisconnected(bool stopCalled = true)
{
SomeClass.someProperty = true;
Console.WriteLine("Hub OnDisconnected {0}\n", Context.ConnectionId);
return (base.OnDisconnected(stopCalled));
}
当我们想要来回传输数据时,我们寻求使用信号R打开连接的能力,但能够知道客户端何时断开连接以便客户端可以继续执行操作。
答案 0 :(得分:0)
如果您创建一个使用单例类来跟踪客户端的集线器,那么如果需要,您可以存储所有连接的客户端,以便在服务器重新联机时重新连接。客户端上确实没有断开事件,只有重新连接的事件。因此很难确定服务器是否已断开连接。我解决这个问题的方法是订阅connection.closed事件。对我来说,我尝试重新连接,失败,我通知用户并退出应用程序。有关保持跟踪客户端的单例方法的信息,我从这个链接开发了我的http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
tcHubProxy(HubConnection hubConnection, StreamWriter writer)
{
mhubConn = hubConnection;
mIHubProxy = hubConnection.CreateHubProxy("CentralHub");
mWriter = writer;
mWriter.AutoFlush = true;
try
{
mhubConn.TraceLevel = TraceLevels.All;
mhubConn.TraceWriter = mWriter;
mhubConn.Closed += MhubConnOnClosed;
mhubConn.Start().Wait();
LogEvent(DateTime.Now, "Info", "Client Connected");
mIHubProxy.On<List<User>>("updateFmds", GetUserFmds);
connected = true;
}
catch (Exception e)
{
if (showMessage)
{
MessageBox.Show(
"There is currently no connection to the server, this application will close, if this issue persists check your network connection or contact support.",
"Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
showMessage = false;
}
connected = false;
showMessage = false;
}
}
public void MhubConnOnClosed()
{
LogEvent(DateTime.Now, "Info", "Client connection to communication hub, attempting to redirect.");
try
{
mhubConn = new HubConnection(ConnectionString);
mhubConn.TraceLevel = TraceLevels.All;
mhubConn.TraceWriter = mWriter;
mIHubProxy = mhubConn.CreateHubProxy("CentralHub");
mhubConn.Start().Wait();
LogEvent(DateTime.Now, "Info", "Reconnection successful.");
mIHubProxy.On<List<User>>("updateFmds", GetUserFmds);
}
catch (Exception e)
{
LogEvent(DateTime.Now, "Error", "Reconnection attempt failed.", e.StackTrace, e.Message);
if (showMessage)
{
MessageBox.Show(
"There is currently no connection to the server, this application will close, if this issue persists check your network connection or contact support.",
"Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
showMessage = false;
}
connected = false;
}
}