블로그 이미지
따시쿵

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2015. 5. 20. 11:50 C# with TCP/IP

프로그램 설명


서버에서 연결되어 있는 클라이언트의 유효성을 체크하는 예제입니다.


1. 윈도우폼의 [도구상자]에서 [Timer] 클래스를 끌어다 폼에 추가 


2. 윈도우폼에 체크 박스를 두어서 체크시 클라이언트 connection 체크를 주기적으로 실행.


   메시지 전송시 헤드만 전송하고 바디 전송은 하지 않습니다. 왜냐하면 유효한지만 

   체크하는 것이므로 연결이 정상적인지, 비정상적인지만 체크하면 됩니다.


   client.SendMessage(BitConverter.GetBytes((int)0));


        #region checkBox1_CheckedChanged
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                //
                timer1.Tick += new EventHandler(TimerEventProcessor);

                // Sets the timer interval to 10 seconds.
                timer1.Interval = 10000;
                timer1.Start();
            }
            else
                timer1.Stop();
        }
        #endregion

        #region TimerEventProcessor
        // This is the method to run when the timer is raised.
        private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            Trace.WriteLine("Event raise the TimerEventProcessor");

            Invoke((MethodInvoker)delegate
            {
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    Client client = listView1.Items[i].Tag as Client;

                    if (client.sck.Connected)
                        client.SendMessage(BitConverter.GetBytes((int)0));  
                    else
                    {
                        this.client_Disconnected(client);
                        DisconnectedClientList(client.sck);
                    }
                }
            });
        }
        #endregion




실행 후


소스 파일 : 

 MyKeepAliveClient1_WindowsForm.zip MyKeepAliveServer1_WindowsForm.zip


posted by 따시쿵