referring to my previous question: Unable to do server reconnection after disconnected in C# winform.
Below is my coding for my client side to do connection with server:
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);
}
}
I do a timer_tick to constantly trying to connect to server. But then a situation occurred: I try connect successfully the server first, then after that I unplug the LAN cable to try to simulate a disconnection. It can't recognize that it is disconnected. It is still in connected state. There's no error message what so ever. Then I plug in the LAN cable back, it can't receive data from server anymore. I think maybe it need to do reconnection again.
How do we let the client know that it has disconnected from server?