参考我之前的问题:Unable to do server reconnection after disconnected in C# winform。
以下是我的客户端与服务器建立连接的编码:
private void timer1_Tick(object sender, EventArgs e)
{
DataProcess();
}
public Socket _serverSocket = null;
private byte[] _recieveBuffer = new byte[128];
void DataProcess()
{
//TimeSpan ts;
try
{
//Thread.Sleep(100);
if (_serverSocket == null || sockState == MySocketState.Disconnected)
{
Console.WriteLine("Trying to connect...");
//ts = DateTime.Now.Subtract(_dLastActivity);
//if (ts.TotalSeconds < 0 || ts.TotalSeconds > 10)
//{
//StartConnect();
SetupServer();
//}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void SetupServer()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Connect(_sIP, Int32.Parse(_sPort));
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
if (_serverSocket.Connected)
{
sockState = MySocketState.Connected;
browser.ExecuteScriptAsync("svrConnect();");
Console.WriteLine("Server connected...");
_serverSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
}
我做了一个timer_tick来不断尝试连接服务器。但后来发生了一种情况: 我尝试首先成功连接服务器,然后我拔掉LAN电缆以尝试模拟断开连接。它无法识别它已断开连接。它仍处于连接状态。什么都没有错误信息。然后我将LAN电缆插回,它无法再从服务器接收数据。我想也许需要再次重新连接。
我们如何让客户知道它已与服务器断开连接?