C#创建Windows Service

前段时间公司的一个项目用到Windows Service,主要用来在Event log 中记录客户端做的一些操作。现整理如下:

1. .net中直接就可以创建Windows Service项目,我使用的是C#,例如:创建一个MyTCPTestWindowsService的工程,重命名Service1.cs为MyTCPTestService.cs,双击该文件,在其设计界面拖入一个System.Diagnostics.EventLog控件,在该控件的属性面板中,将Log改为MyTCPTestSourceLog,Source改为MyTCPTestLogSource。

2. 单击属性面板下面灰色区域中的“添加安装程序”链接。默认情况下,向项目中添加包含两个安装程序的组件类。将该组件命名为ProjectInstaller,它包含的安装程序分别是服务的安装程序和服务关联进程的安装程序。  

3. 在MyTCPTestService.Designer.cs代码的方法private void InitializeComponent()增加this.ServiceName = "MyTCPTestService"; 为自己的Service命名。

4. 查看MyTCPTestService.cs的代码(右键选中-->查看代码) 

  Thread newThread;
        //TCP Listner for Socket
        public TcpListener tcpServer;
        //Creating a Network Stream
        public NetworkStream ns;
        //Creating a Stream reader
        public StreamReader sr;
        //Creating a Stream Writer
        public StreamWriter sw;
        //Creating a Socket
        public Socket sc;
        public string clientReq;


        public TCPTestService()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("MyTCPTestLogSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource("MyTCPTestLogSource", "MyTCPTestSourceLog");
            }

            //Name of EventLog
            eventLog.Source = "MyTCPTestLogSource";
            eventLog.Log = "MyTCPTestSourceLog";
        }
 
		// The main entry point for the process
		static void Main()
		{
			System.ServiceProcess.ServiceBase[] ServicesToRun;
	        //New Service Created.
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new TCPTestService() };
            //Run the New Service.
			System.ServiceProcess.ServiceBase.Run(ServicesToRun);	
		}

        protected override void OnStart(string[] args)
        {
            tcpServer = new TcpListener(new IPEndPoint(IPAddress.Any, 8080));
            eventLog.WriteEntry("MyTCPTestServerService started");
            newThread = new Thread(new ThreadStart(ThreadFunction));
            newThread.IsBackground = true;
            newThread.Start();
        }

        protected override void OnStop()
        {
            eventLog.WriteEntry("MyTCPTestServerService stopped");
            newThread.Abort();
        }

        /// <summary>
        /// Continue this service.
        /// </summary>
        protected override void OnContinue()
        {
            eventLog.WriteEntry("MyTCPTestServerService is continuing in working");
        }

其中,TCPTestService()里面后面的代码都是配置EventLog的。OnStart和OnStop方法是Service启动和停止的时候调用的方法,代码都很简单,只是简单的记录了日志。注意在OnStart中,我创建了一个后台执行的线程,该线程运行的时候会调用ThreadFunction方法,这个方法是自定义的:

  /// <summary>
        /// For Listening Socket.
        /// </summary>
        public void ThreadFunction()
        {
            tcpServer.Start(4);
            while (true)
            {
                sc = tcpServer.AcceptSocket();
                eventLog.WriteEntry(" Client Respose Received");
                try
                {
                    if (sc.Connected)
                    {
                        try
                        {
                            ns = new NetworkStream(sc);
                            sr = new StreamReader(ns);
                            sw = new StreamWriter(ns);
                            clientReq = sr.ReadLine();
                        }
                        catch (OutOfMemoryException ex)
                        {
                            eventLog.WriteEntry("Problem occur while reading stream:-" + ex.Message);
                            eventLog.WriteEntry("MyTCPTestServerService is Stopping");
                            OnStop();
                        }
                        catch (IOException ex)
                        {
                            eventLog.WriteEntry("Problem occur while intializing network stream:-" + ex.Message);
                            eventLog.WriteEntry("MyTCPTestServerService is Stoping");
                            OnStop();
                        }
                        eventLog.WriteEntry("Current Command:" + clientReq);
                    }
                }
                catch (IOException ex)
                {
                    eventLog.WriteEntry("Exception occur in the service:-" + ex.Message);
                    sw.WriteLine("Stop");
                }
                try
                {
                    sw.Close();
                    sr.Close();
                    ns.Close();
                    sc.Close();
                    clientReq = null;
                    eventLog.WriteEntry(" Request completed");
                }
                catch (IOException ex)
                {
                    eventLog.WriteEntry("Problem occur while closing the socket:-" + ex.Message);
                    eventLog.WriteEntry("MyTCPTestServerService is Stoping");
                    OnStop();
                }
            }
        }

  在该方法中,创建了一个TCPListener,监听8080端口,读取该端口接受的数据,并记录在定义好的Event Log中。

5. 修改工程属性窗口的Start project。 

ok,Service的代码已经完毕,下一篇(http://canbeatle.iteye.com/blog/698442)将介绍怎样制作安装项目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值