我的任务非常复杂。我有2个项目,通过TCP连接(监听器和客户端)互相联系。如果我在最近5秒内收到客户端的消息,我想检查服务器程序。如果客户端程序连接到服务器,则每3秒自动发送一次消息(通过单击“连接到服务器”按钮连接功能)。
这里的高级是我需要服务器做其他事情所以它必须在线程中。 我知道服务器包含在客户端发送FIRST消息时启动的线程。当线程启动时,它每隔5秒启动一次计时器,它会检查每5秒增加一次的变量或每次获取消息(当我收到消息时,我会停止计时器并再次从头开始)。
我试图这样做,但没有成功。我将添加我的代码,但它不起作用。如果有人有想法,我会很高兴我试了好几个小时。
代码:
//Definition
private int radarPulseNumber;
private int counterTimer; // It the counter of the timer tick's
private bool ifItFirstPulse = true;
private System.Timers.Timer timerForPulse;
private Thread TimerCountRadarPulse;
// Start the thread
TimerCountRadarPulse = new Thread(() => { ifHaveConnection(); });
TimerCountRadarPulse.Start();
private void DrawForPulseMessage(object ls)
{
Dispatcher.Invoke(new Action(() =>
{
if (ifItFirstPulse)
{
ifItFirstPulse = false;
// Create a timer with a 5 second interval.
timerForPulse = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
timerForPulse.Elapsed += OnTimedEvent;
timerForPulse.Enabled = true;
}
else
{
counterTimer++;
timerForPulse.Stop();
timerForPulse.Start();
}
radarPulseNumber++; // It is the counter how much recieve message we got from the client
lbl_Pulse.Content = "" + radarPulseNumber.ToString();
ImageConnect.Visibility = Visibility.Visible;
ImageDisconnect.Visibility = Visibility.Collapsed;
}));
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
counterTimer++;
}
private void ifHaveConnection() // Actually it's the function that checks the tick's of timer vs the actually recieves.
{
if (l.numOfPulseRecieves != radarPulseNumber) // l.numOfPulseRecives is an field in object who gets the number of recieve from client
{
Dispatcher.Invoke(new Action(() =>
{
// Initiallized variables for reConnect to server.
radarPulseNumber = 0;
counterTimer = 0;
ImageConnect.Visibility = Visibility.Collapsed;
ImageDisconnect.Visibility = Visibility.Visible;
}));
}
}