블로그 이미지
따시쿵

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. 14. 14:23 C# with Service Program

프로그램 설명


윈도우즈 서비스를 이용해서 Tcp 통신을 하는 예제입니다.

서버는 서비스로 만들었으며, 클라이언트는 윈도우즈 폼으로 작성 했습니다.

서버에서 클라이언트와 통신을 할 때 각 단계별로 로그 파일을 쌓아서 진행 상황을 체크 합니다.


1. app.config 파일에 실제 로그를 쌓을 경로 이름을 기술합니다.


    
      
    
  
     
        
    


Debug 폴더 안에서 파일을 실행 시키면 System.IO.Directory.GetCurrentDirectory() method 를 이용해서 현재의 위치를 찾을 수 있지만, 서비스 프로그램에서 실행 파일의 현재 위치를 찾게되면 64비트 컴퓨터에서는 C:\Windows\SysWOW64 폴더를 찾습니다. 따라서 SysWOW64 폴더 하위에 Log 폴더를 생성합니다. 


app.config 파일 안에서 로그 파일의 위치를 풀경로를 이용해서 명시해 줍니다.


2. 로그 파일 이용 방법 

로그 라이브러리 : LogFile.cs

LogFile.WriteLog("OnStart");

LogFile.WriteLog(ex.Message, LogFile.LogCode.Error);


3. 윈도우즈 서비스가 설치된 컴퓨터의 방화벽에서 해당하는 포트를 열러 주어야 합니다.



실행 화면







프로그램 작성 순서


1. 서비스 프로그램의 OnStart() 에서 소켓 관련 thread 를 생성합니다.


        protected override void OnStart(string[] args)
        {
            LogFile.WriteLog("OnStart");
                        
            // Create the sub working thread...
            Thread thread_handler = new Thread(socketMain.StartSocket);
            thread_handler.IsBackground = true;
            thread_handler.Start();
        }


2. 일반적인 소켓 서버 클래스를 작성합니다.


        static TcpListener server = null;
        #region StartSocket
        public void StartSocket()
        {
            LogFile.WriteLog("StartSocket");

            try
            {
                // set the TcpListener on port 14000
                Int32 port = 14000;
                
                // create the server socket & start
                server = new TcpListener(IPAddress.Any, port);
                server.Start();

                // buffer for reading data
                byte[] bytes = new byte[2014];
                string data = string.Empty;

                // waiting for a client connection
                while (true)
                {
                    LogFile.WriteLog("Waiting for a connection....");

                    TcpClient client = server.AcceptTcpClient();
                    LogFile.WriteLog("Connected!");

                    NetworkStream stream = client.GetStream();

                    // read the message from client and send the message to client
                    int bytesRead = 0;
                    while ((bytesRead = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = Encoding.UTF8.GetString(bytes, 0, bytesRead);
                        LogFile.WriteLog(string.Format("Received : {0}", data));

                        data = data.ToUpper();

                        byte[] msg = Encoding.UTF8.GetBytes(data);

                        stream.Write(msg, 0, msg.Length);
                        LogFile.WriteLog(string.Format("Sent : {0}", data));
                    }

                    client.Close();
                }

            }
            catch (SocketException se)
            {
                LogFile.WriteLog(se.Message, LogFile.LogCode.Error);
            }
            catch (Exception ex)
            {
                LogFile.WriteLog(ex.Message, LogFile.LogCode.Error);
            }
            finally
            {
                server.Stop();
            }

        }
        #endregion


3. OnStop method 에서 socket server를 닫습니다.


        protected override void OnStop()
        {
            LogFile.WriteLog("OnStop");

            socketMain.StopSocket();
        }




소스 파일 :

MyNewService2.zip   MyNewService2_Client.zip

'C# with Service Program' 카테고리의 다른 글

[C#] 서비스 프로그램 - 디버깅  (0) 2015.05.15
[C#] 서비스 프로그램 - 1  (0) 2015.05.11
posted by 따시쿵