This is the code block. I will explain details below.
public static bool isConnected;
public MasterClient() //Master Constructor
{
timer1.Interval = 1000;
isConnected = false;
}
private void connectCallback(IAsyncResult ar)
{
try
{
_ClientSocket.EndConnect(ar);
//Global.Meuser = Environment.MachineName;
BeginReceive();
Invoke((MethodInvoker)delegate
{
tslStatus.Text = "Connected";
btnConnect.Text = "Disconnect";
tslStatus.Image = Image.FromFile(Global.path + @"\image\status\online.png");
lbllocalIP.Text = _ClientSocket.LocalEndPoint.ToString();
isConnected = true;
//this.WindowState = FormWindowState.Minimized;
});
}
catch (SocketException ex)
{
isConnected = false;
}
finally
{
if (isConnected == false)
{
counter = 0;
timer1.Start();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
isConnected = false;
counter += 1;
if (counter > 45)
{
counter = 0;
timer1.Stop();
AutoStart();
}
}
public void AutoStart()
{
if (btnConnect.Text == "Connect")
{
if (IsRunning == false)
{
_buffer = new byte[8192];
_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ClientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(txtServerIP.Text), 9192), new AsyncCallback(connectCallback), null);
}
}
else if (btnConnect.Text == "Disconnect")
{
if (IsRunning == true)
{
CloseClient();
btnConnect.Text = "Connect";
lbllocalIP.Text = "None";
tslStatus.Text = "Disconnected";
tslStatus.Image = Image.FromFile(Global.path + @"\image\status\offline.png");
}
}
}
The timer should start after timer1.Start()
event raised in the finally
block in the connectCallback
method.
When I check using a breakpoint, after timer1.Start()
is called it will change to Enabled=true state.
I have taken the timer control from the toolbox and set its interval to 1000.
But still timer1.Tick
event is not raising.
Condition: When server is not running at that time SocketException will fire, at same time I need to start timer so it will try after 45 seconds to connect to server again and if it fails it will be requeue.