简体   繁体   English

C#Windows服务编写

[英]C# windows service writing

I trying to create a windows service using C#. 我试图使用C#创建Windows服务。 Service must open TCPListener on 5089 port and start dispatching commands. 服务必须在5089端口上打开TCPListener并开始调度命令。 But if I put my TCPListener initialization code and starting dispatching thread into OnStart() service method, my service not starts (Admin panel -> Administration -> Services -> MyService -> Start) 但是,如果我将TCPListener初始化代码放入OnStart()服务方法中并开始分配线程,则我的服务无法启动(管理面板->管理->服务-> MyService->启动)

protected override void OnStart(string[] args)
{
    _server = new CommandServer("LocalCommandServer", "192.168.10.150", false);

    _server.Initialize("LocalCommandServer", "192.168.10.150"); // In this method starts dispatching thread
}

protected override void OnStop()
{
    _server.Dispose();
}

How I can start my TCPListener and dispatching thread in windows service? 如何在Windows服务中启动TCPListener和调度线程?

 public class CommandServer : IDisposable
{
    private IPAddress _serverIP;

    private bool _mayDispatch;

    public string Name { get; set; }

    private Queue<string> _commandsQueue;
    private TcpListener _commandListener;
    private Thread _commandListenerThread;
    private Thread _mainThread;

    public CommandServer(string name, string serverIP, bool initialize)
    {
        if (initialize)
            Initialize(name, serverIP);
    }

    public bool Initialize(string name, string serverIP)
    {
        _serverIP = IPAddress.Parse(serverIP);

        _mayDispatch = true;

        Name = name;

        _commandsQueue = new Queue<string>();


        _commandListener = new TcpListener(_serverIP, 5089);

        _commandListenerThread = new Thread(TcpListenerThread);

        _commandListener.Start();
        _commandListenerThread.Start();

        _mainThread = Thread.CurrentThread;

        StartDispatching();

        return true;

    }

    private void StartDispatching()
    {
        while (_mayDispatch)
        {
            if (_commandsQueue.Count > 0)
                DispatchCommand(_commandsQueue.Dequeue());
        }
        _commandListener.Stop();
        _commandListenerThread.Abort();
    }

    public void DispatchCommand(string cmnds)
    {
        var cmnd = cmnds.Split(' ');
        switch (cmnd[0].ToLower())
        {
            case "terminate":
                _mayDispatch = false;

                break;

            case "start":

                var proc = new Process
                       {
                           StartInfo =
                               {
                                   FileName = cmnd[1],
                                   CreateNoWindow = false,
                                   UseShellExecute = true
                               }
                       };
                proc.Start();

                break;

        }
    }

    public void TcpListenerThread()
    {
        while (true)
        {
            var client = _commandListener.AcceptTcpClient();

            if (client.Connected)
            {
                var clientStream = client.GetStream();
                var buff = new List<byte>();

                while (clientStream.CanRead)
                {
                    var b = clientStream.ReadByte();
                    if (b == -1)
                        break;
                    buff.Add((byte)b);
                }

                var command = Encoding.ASCII.GetString(buff.ToArray());

                _commandsQueue.Enqueue(command);

                System.Diagnostics.Debug.WriteLine("Queued: " + _commandsQueue.Count);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Not connected");
            }

        }

    }

    public void Dispose()
    {
        _commandListener.Stop();
        _commandListenerThread.Abort();
    }
}

TCPListener初始化代码可能会引发一些异常,尝试通过将Debugger.Launch()作为OnStart的第一条语句来调试服务,然后查看发生了什么。

You need to return from the OnStart event. 您需要从OnStart事件返回。

See a sample here http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx 在此处查看示例http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

I found it! 我找到了!

  protected override void OnStart(string[] args)
        {
            _server = new CommandServer("LocalCommandServer", "192.168.10.150", false);
            _serverThread = new Thread(ServerThread);
            _serverThread.Start();
        }

        private void ServerThread()
        {
            _server.Initialize("LocalCommandServer", "192.168.10.150");
        }

        protected override void OnStop()
        {
            _serverThread.Abort();
            _server.Dispose();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM