gpt4 book ai didi

connection - 从客户端检测 SignalR 中丢失的连接

转载 作者:行者123 更新时间:2023-12-04 16:47:34 30 4
gpt4 key购买 nike

我正在将一个简单的应用程序连接到托管我的网络应用程序的服务器。我的网络应用程序使用 SignalR 2。一切都很顺利,我的小应用程序可以与网络应用程序同步并接收从它发送的消息。但是,当网页更新或服务器重新启动并失去连接时,应用程序无法理解与服务器的连接丢失。以下是我的代码:

// initializing connection
HubConnection connection;
IHubProxy hub;

connection = new HubConnection(serverAddress);
hub = connection.CreateHubProxy("MyPanel");
hub.On<string>("ReciveText", (msg) => recieveFromServer(msg));

线程每 1 分钟检查一次连接,但每次检查时,连接状态为“已连接”,而服务器端的连接丢失。我在这里遗漏了什么吗?

if (connection.State == ConnectionState.Disconnected)
{
// try to reconnect to server or do something
}

最佳答案

你可以尝试这样的事情:

来自signalR官方例子。

connection = new HubConnection(serverAddress);    
connection.Closed += Connection_Closed;

/// <summary>
/// If the server is stopped, the connection will time out after 30 seconds
/// the default, and the `Closed` event will fire.
/// </summary>
void Connection_Closed()
{
//do something
}

您也可以像这样使用 StateChanged 事件:

connection.StateChanged += Connection_StateChanged;

private void Connection_StateChanged(StateChange obj)
{
MessageBox.Show(obj.NewState.ToString());
}

编辑

您可以尝试每 15 秒重新连接一次:

private void Connection_StateChanged(StateChange obj)
{

if (obj.NewState == ConnectionState.Disconnected)
{
var current = DateTime.Now.TimeOfDay;
SetTimer(current.Add(TimeSpan.FromSeconds(30)), TimeSpan.FromSeconds(10), StartCon);
}
else
{
if (_timer != null)
_timer.Dispose();
}
}

private async Task StartCon()
{
await Connection.Start();
}

private Timer _timer;
private void SetTimer(TimeSpan starTime, TimeSpan every, Func<Task> action)
{
var current = DateTime.Now;
var timeToGo = starTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
return;
}
_timer = new Timer(x =>
{
action.Invoke();
}, null, timeToGo, every);
}

关于connection - 从客户端检测 SignalR 中丢失的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519645/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com