信号R -处理集线器外的断开连接
本文关键字:断开 连接 集线器 处理 信号 | 更新日期: 2023-09-27 17:52:54
我试图完成从控制器方法发送数据到我的客户端方法,该方法在实例客户端断开连接时返回响应。
控制器目前. .
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";
}
因为我们知道客户端从hub重写方法断开连接…
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打开连接的能力,但是能够知道客户端何时断开连接,以便客户端可以继续做事情。
如果您创建了一个使用单例类来跟踪客户端的集线器,那么如果您需要,您可以存储所有已连接的客户端,以便在服务器重新联机时能够重新连接。在客户端上实际上没有断开连接事件,只有重新连接事件。因此,很难确定服务器是否已断开连接。我解决这个问题的方法是订阅连接。关闭事件。对我来说,我尝试重新连接一次,如果失败,我通知用户并退出应用程序。有关跟踪客户端的单例方法的信息,我从以下链接开发了自己的方法: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;
}
}