简体   繁体   English

在c#中作为Windows服务运行时,TCP / IP套接字不从机器读取数据

[英]TCP/IP Socket is not reading data from machine when running as Windows Service in c#

I have a simple TCP/IP program to read data from a machine and write it into text file. 我有一个简单的TCP / IP程序来从机器读取数据并将其写入文本文件。 I want to run it as Windows Service so that data gets written into text file continuously with out any intervention. 我想将它作为Windows服务运行,以便数据连续写入文本文件而无需任何干预。 Now when I try to run the program under debug mode of Visual Studio, it is reading the data from the machine and saving into text file, but as soon as I add it as Windows Service and try to start the service, it is giving following error message.. 现在,当我尝试在Visual Studio的调试模式下运行程序时,它正在从机器读取数据并保存到文本文件中,但是一旦我将其添加为Windows服务并尝试启动服务,它就会给出以下内容错误信息..

windows service could not start the service on the local computer

error:1053 The service did not respond to the start or the control request in a timely  fashion 

Here is my main applications code.. 这是我的主要应用程序代码..

static void Main()
    {

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service1() 
        };
        ServiceBase.Run(ServicesToRun);

    }

Here is my code to communicate to the machine using TCP/IP and read/write data into text file.. 这是我的代码,使用TCP / IP与机器进行通信,并将数据读/写到文本文件中。

        protected override void OnStart(string[] args)
    {
        ipaddress = "";
        int port = int.Parse("");
        textfileSaveLocation = "";

        byte[] data = new byte[1024];
        string stringData;

        IPAddress ipadd = IPAddress.Parse(ipaddress);
        IPEndPoint ipend = new IPEndPoint(ipadd, port);
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.NoDelay = false;
        try
        {
            sock.Connect(ipend);

        }
        catch (Exception dfg)
        {    
            return;
        }
        try
        {
            buf = String.Format("SMDR", "PCCSMDR");
            bBuf = Encoding.ASCII.GetBytes(buf);
            sock.Send(bBuf);

            while (true)
            {
                data = new byte[1024];
                int recv = sock.Receive(data);
                stringData = Encoding.ASCII.GetString(data, 0, recv);

                string df = "";
                try
                {
                    FileStream dr = new FileStream(textfileSaveLocation, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader fg = new StreamReader(dr);
                    df = fg.ReadToEnd();
                    fg.Dispose();
                    dr.Dispose();
                }
                catch (Exception dfjdfs)
                {
                }

                try
                {
                    FileStream cd = new FileStream(textfileSaveLocation, FileMode.Create);
                    StreamWriter cdf = new StreamWriter(cd);
                    cdf.WriteLine(df);
                    cdf.WriteLine(stringData);
                    cdf.Dispose();
                    cd.Dispose();
                }
                catch (Exception hgy)
                {
                }
            }
            sock.Shutdown(SocketShutdown.Both);
            sock.Close();
        }
        catch (Exception DFGFD)
        {
        }
    }

My only aim with this program is to run it as Windows Service through installer and start the service. 我唯一的目标是通过安装程序将其作为Windows服务运行并启动该服务。 Once the service is started, it should read the data from the given ip and port of the machine and save it into text file. 一旦服务启动,它应该从机器的给定ip和端口读取数据并将其保存到文本文件中。 Also I need this service to continuously monitor for the data from the machine and once new data comes to the machine, it should read and write into the text file. 此外,我需要此服务来持续监控来自机器的数据,一旦新数据进入机器,它应该读取并写入文本文件。

Do I need to implement Multi-threading in the program? 我是否需要在程序中实现多线程?

The system expects the OnStart method to return in a timely fashion (~30 seconds), so long-running tasks like monitoring for data need to be moved to another thread. 系统期望OnStart方法及时返回(约30秒),因此需要将长时间运行的任务(如监视数据)移动到另一个线程。 This can be as simple as: 这可以很简单:

private System.Threading.Thread _thread;
protected override void OnStart(string[] args)
{
    _thread = new Thread(DoWork);
    _thread.Start();
}

private void DoWork()
{
    // create and monitor socket here...
}

Note that while your while (true) loop is sufficient to keep the thread running, it makes it difficult to stop it when the service stops. 请注意,虽然while (true)循环足以使线程保持运行,但在服务停止时很难停止它。 For this, I use a ManualResetEvent like so. 为此,我使用像这样的ManualResetEvent

using System.Threading;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);

private void DoWork()
{
    // initialize socket and file

    // thread loop
    while (!_shutdownEvent.Wait(0))
    {
        // read socket, write to file
    }

    // close socket and file
}

protected override void OnStop()
{
    _shutdownEvent.Set();
    _thread.Join();  // wait for thread to stop
}

I agree with Matt's answer. 我同意马特的回答。

Also, In general , it is good to add an option to debug your service, here is an example: 此外,通常,最好添加一个选项来调试您的服务,这是一个例子:

     protected override void OnStart(string[] args)
        {         
                bool launchDebugger = false;
                if (args.Count() > 0)
                {
                    launchDebugger = args[0].ToLower() == "debug";
                }


                if (launchDebugger)
                {                   
                   Debugger.Launch();
                }    
} 

When you run the service with an argument: "debug", it will trigger a fake exception, allowing you to debug the service with visual studio. 当您使用参数“debug”运行服务时,它将触发假异常,允许您使用visual studio调试服务。

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

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