gpt4 book ai didi

c# - 网络断开时的WebSocket重新连接问题

转载 作者:行者123 更新时间:2023-12-03 12:04:00 44 4
gpt4 key购买 nike

当我断开网络连接并再次重新连接时,我正在使用下面的套接字功能从套接字服务器接收数据,然后再次连接套接字应用程序停止接收数据。我还尝试添加一个计时器,该计时器每20秒检查一次套接字的状态,但不起作用。有什么建议吗?

private WebSocket client;  //before form_load

private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host);

client.OnOpen += (ss, ee) =>
{
MessageBox.Show(string.Format("Connected to {0} successfully ", host));
};

client.OnError += (ss, ee) =>
{
MessageBox.Show(" Error: " + ee.Message);
};

client.OnMessage += (ss, ee) =>
{
MessageBox.Show("Message: " + ee.Message);
};

client.OnClose += (ss, ee) =>
{
MessageBox.Show(string.Format("Disconnected with {0}", host));
};

client.Connect();
}

private void timer1_Tick(object sender, EventArgs e)
{
if(client.ReadyState.ToString()=="Closed")
{
client.Close();
client = new WebSocket(host);
client.Connect();
}

}

最佳答案

您没有提到您使用的Web套接字库/程序包。这是一个使用WebSocket4Net的简单工作重新连接示例。

由于使用了AutoSendPing,当网络发生故障时,它会关闭连接,如果套接字已关闭,计时器会尝试重新连接。

private WebSocket client;

private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host)
{
EnableAutoSendPing = true,
AutoSendPingInterval = 10,
};

client.Opened += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Connected");
};

client.Error += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Error {ee.Exception}");
};

client.MessageReceived += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Message: {ee.Message}");
};

client.Closed += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Disconnected");
};

client.Open();
}

private void timer1_Tick(object sender, EventArgs e)
{
if (client.State == WebSocketState.Closed)
{
client.Open();
System.Diagnostics.Debug.WriteLine("Trying to reconnect by timer");
}
}

关于c# - 网络断开时的WebSocket重新连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256555/

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