当前位置:编程学习 > C#/ASP.NET >>

C#监听端口的windows服务,有点疑问请大家来看看,有代码框架,马上给分!~~

我写了一个监听端口的windows服务,

当服务第一次启动,并没有TCP连接,停止服务则在进程中没有winService.exe这个进程,但是一但有TCP连接一次后,即使关闭客户段,停止该服务,在进程中还有这个winService.exe进程存在。


代码如下:thread 为全局变量

//启动服务代码
public override  void OnStratr()
{
thread = new Thread(new ThreadStart(this.Listeners));
thread.Start();
}

//停止服务代码

public override  void OnStop()
{
thread.Abort();
}


//多线程监听

private void Listeners()
{
IPAddress ip=IPAddress.Parse(ipStr);
listener = new TcpListener(ip,portNum);
listener.Start();

while (true) 
{
try
{
client = listener.AcceptTcpClient(); 
监听是否有新的TCP连接,没有就处于堵塞状态
如果有则开启一个线程来处理

thread= new Thread(new ThreadStart(this.mainServer));

thread.Start();

}

//处理数据主程序略
private void mainServer()
{
////
////
}

--------------------编程问答-------------------- 是不是都去吃饭了啊,怎么没有人啊 --------------------编程问答-------------------- 退出的时候thread.join()了没有啊 --------------------编程问答-------------------- to 楼上的,没有呢 --------------------编程问答-------------------- 怎么还没有人呢 --------------------编程问答-------------------- 楼主的问题解决没有,帮顶。如果解决了写下解决的方法阿。 --------------------编程问答-------------------- 线程问题,开始服务后,线程启动,但是现在作为前台线程,前台线程和主程序是同一级别,所以当停止服务了,线程没有结束,所以程序没有结束.

解决办法,把它做为后台线程,加一句:
thread.isback....//我现在没有编译器,这个词记不清楚了

随便说句,将前台线程放到死循环里面是非常卡的事情,呵呵. --------------------编程问答-------------------- //启动服务代码
public override  void OnStratr()
{
thread = new Thread(new ThreadStart(this.Listeners));
//
//加这个地方
thread.Start();
} --------------------编程问答-------------------- 这个问题我最近也遇到了,是你在推出程序的时候没有关闭线程的问题。可以在主线程退出的时候手动调用thread.abort --------------------编程问答-------------------- windows服务不能由自己编写代码来结束,必须由外部的windows服务监视器来结束.关于远程机子的windows监控问题可以采用System.Management命名空间下的ManagementClass和ManagementObject类来完成.关键代码如下:
class partial Win32ServiceManage
    {
        private ManagementClass severManager;
        private string strPath;
        private List<Win32Service> _ServiceList;
        private bool _IsLocal;
        private string _HostName;
        private string _UserName;
        private string _Password;

        public bool IsLocal
        {
            get { return _IsLocal; }
        }

        public string HostName
        {
            get { return _HostName; }
        }

        public string UserName
        {
            get { return _UserName; }
        }

        public string Password
        {
            get { return _Password; }
        }

        public Win32ServiceManage() 
        {
            _IsLocal = true;
            _ServiceList = new List<Win32Service>();
        }

        public Win32ServiceManage(string host, string userName, string password)
        {
            _IsLocal = false;
            _ServiceList = new List<Win32Service>();
            strPath = "\\\\" + host + "\\root\\cimv2:Win32_Service";
            severManager = new ManagementClass(strPath);
            if (userName != string.Empty && userName != null 
                && password!=string.Empty && password!=null
                && host!=string.Empty && host!=null)
            {
                _HostName = host;
                _Password = password;
                _UserName = userName;
                ConnectionOptions option = new ConnectionOptions();
                option.Username = _UserName;
                option.Password = _Password;               
                ManagementScope mscope = new ManagementScope(strPath, option);
                severManager.Scope = mscope;
            }
        }

        public static bool RemoteConnectValidate(string host, string userName, string password)
        {
            string path = "\\\\" + host + "\\root\\cimv2";
            ConnectionOptions option = new ConnectionOptions();
            option.Password = password;
            option.Username = userName;
            ManagementScope mscope = new ManagementScope(path, option);
            try
            {
                mscope.Connect();
            }
            catch{}           
            return mscope.IsConnected;
        }

       

        public List<Win32Service> GetServiceList()
        {
            _ServiceList.Clear();
            if(_IsLocal==false)
            {                
                foreach (ManagementObject service in severManager.GetInstances())
                {
                    _ServiceList.Add(new Win32Service(service));
                }               
            }
            else
            {
               
                try
                {
                    SelectQuery query = new SelectQuery("Select * From Win32_Service");
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                    foreach(ManagementObject service in searcher.Get())
                    {

                        _ServiceList.Add(new Win32Service(service));
                    }
                }
                catch{}                
            }
            return _ServiceList;
        }

        public List<Win32Service> GetServiceList(string serviceName)
        {
            return GetServiceList(new string[] { serviceName });
        }

        public List<Win32Service> GetServiceList(string[] servicesName)
        {
            List<Win32Service> servicess = new List<Win32Service>();   
            if(_IsLocal==false)
            {
                foreach (string name in servicesName)
                {
                    ManagementObject service = severManager.CreateInstance();
                    service.Path = new ManagementPath(".Name=\"" + name + "\"");                   
                    servicess.Add(new Win32Service(service));
                }
            }
            else
            {
                foreach(Win32Service winService in _ServiceList)
                {
                    foreach(string name in servicesName)
                    {
                        if(winService.Name==name)
                        {
                            servicess.Add(winService);
                        }
                    }
                }
            }       
            return servicess;
        }

        } --------------------编程问答-------------------- partial class  Win32ServiceManage
{

        public string StartService(string service)
        {
            string message = string.Empty;
            try
            {
                if(_IsLocal==false)
                {
                    ManagementObject myservice = severManager.CreateInstance();
                    myservice.Path = new ManagementPath(strPath + ".Name=\"" + service + "\"");
                    Win32Service winService = new Win32Service(myservice);
                    winService.StartService();
                }
                else
                {
                    List<Win32Service> servicelist = GetServiceList(service);
                    servicelist[0].StartService();
                }               
            }
            catch (ManagementException e)
            {
                message = e.Message;
            }
            return message;
        }

        public string PauseService(string service)
        {
            string message = string.Empty;
            try
            {
                if(_IsLocal==false)
                {
                    ManagementObject myservice = severManager.CreateInstance();
                    myservice.Path = new ManagementPath(strPath + ".Name=\"" + service + "\"");
                    Win32Service winService = new Win32Service(myservice);
                    winService.PauseService();
                }
                else
                {
                    List<Win32Service> servicelist = GetServiceList(service);
                    servicelist[0].PauseService();
                }      
            }
            catch (ManagementException e)
            {
                message = e.Message;
            }
            return message;
        }

        public string ResumeServie(string service)
        {
            string message = string.Empty;
            try
            {
                if(_IsLocal==false)
                {
                    ManagementObject myservice = severManager.CreateInstance();
                    myservice.Path = new ManagementPath(strPath + ".Name=\"" + service + "\"");
                    Win32Service winService = new Win32Service(myservice);
                    winService.ResumeServie();
                }
                else
                {
                    List<Win32Service> servicelist = GetServiceList(service);
                    servicelist[0].ResumeServie();
                }      
            }
            catch (ManagementException e)
            {
                message = e.Message;
            }
            return message;
        }

        public string StopService(string service)
        {
            string message = string.Empty;
            try
            {
                if(_IsLocal==false)
                {
                    ManagementObject myservice = severManager.CreateInstance();
                    myservice.Path = new ManagementPath(strPath + ".Name=\"" + service + "\"");
                    Win32Service winService = new Win32Service(myservice);
                    winService.StopService();
                }
                else
                {
                    List<Win32Service> servicelist = GetServiceList(service);
                    servicelist[0].StopService();
                }     
            }
            catch (ManagementException e)
            {
                message = e.Message;
            }
            return message;
        }
}
1.该类实现了监控本地和远程Windwos服务两种功能.
其中构造函数语句:
 strPath = "\\\\" + host + "\\root\\cimv2:Win32_Service";用于连接远程服务的路径.
2.RemoteConnectValidate方法用于检测是否能连到远程主机.
3.当调用了构造函数之后,就可以采用ManagementClass类的CreateInstance方法创建ManagementObject对

象,然后为该对象的Path属性赋值以便定向到某个windows服务.
4.当调用了构造函数之后,就可以采用ManagementClass类的GetInstances方法得到所有的

ManagementObject对象集合,因为在构造函数中已经指明了windows服务路径,因此GetInstances方法是得

到某台机子上所有的windows服务
5.如果要停止某个windows服务,只需调用StartService方法限可. --------------------编程问答-------------------- mark --------------------编程问答-------------------- 谢谢了  对我有用了 
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,