我有客户端服务器应用程序(Lan base)。最初,客户端应用程序成功连接到服务器,但稍后在运行时由于某种原因(例如服务器计算机关闭)导致连接丢失。这会触发类似UNABLE TO CONNECT TO HOST
的错误。如何在运行时检查连接状态?
代码如下
连接类
using MySql.Data.MySqlClient;
namespace Connection_Checker
{
public class Connection
{
public static MySqlConnection cnn = new MySqlConnection("Server=localhost;Database=arc;User Id=root;Password=root;");
}
}
表格
private void Form1_Load(object sender, EventArgs e)
{
Connection.cnn.Open();
}
//and timer
private void timer1_Tick(object sender, EventArgs e)
{
if (Connection.cnn.State == ConnectionState.Open)
{
this.Text = "Connected";
}
else
{
this.Text = "Disconnected";
return;
}
}
我的计时器是enable = true
答案 0 :(得分:1)
如果我是你的形式,我不会在表单加载事件中打开连接。
相反,我将获取数据的方法将是这样的
using MySql.Data.MySqlClient;
namespace Connection_Checker
{
public class Connection
{
public static connectionString = "Server=localhost;Database=arc;User Id=root;Password=root;";
}
}
以表格
private void GetData()
{
try{
using (MySqlSqlConnection connection = new MySqlSqlConnection(Connection.connectionString ))
{
connection.Open();
//GetData
connection.Close();
}
}
catch
{
MessageBox.Show("An error occurred while trying to fetch Data");
}
}
private void Form1_Load(object sender, EventArgs e)
{
//I would avoid this.
// Connection.cnn.Open();
}
//I am not sure why you are having this.
private void timer1_Tick(object sender, EventArgs e)
{
//if (Connection.cnn.State == ConnectionState.Open)
//{
// this.Text = "Connected";
//}
//else
//{
// this.Text = "Disconnected";
// return;
//}
}
答案 1 :(得分:0)
捕获传输错误不会告诉您何时连接失败。它只告诉您在尝试使用它时连接不可用。
根据您的示例使用计时器进行连续状态监控,使用此扩展方法直接查询TCP连接状态。
public static class Extensions
{
/// <summary>
/// Obtain the current state of the socket underpinning a TcpClient.
/// Unlike TcpClient.Connected this is reliable and does not require
/// capture of an exception resulting from a failed socket write.
/// </summary>
/// <param name="tcpClient">TcpClient instance</param>
/// <returns>Current state of the TcpClient.Client socket</returns>
public static TcpState GetState(this TcpClient tcpClient)
{
var foo = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()
.SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
return foo != null ? foo.State : TcpState.Unknown;
}
}
但是,正如其他人在评论中已经提到的那样,您对连续连接的依赖可能反映了您的应用程序中的严重设计缺陷。你应该留意你给出的建议并重新设计你的应用程序。占用连接会严重限制可扩展性,并且不会让您受到网络管理员或数据库管理员的欢迎。