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

标签 c# multithreading sockets tcp windows-services

我有一个简单的 TCP/IP 程序来从机器读取数据并将其写入文本文件。我想将它作为 Windows 服务运行,以便在没有任何干预的情况下将数据连续写入文本文件。现在,当我尝试在 Visual Studio 的 Debug模式下运行该程序时,它正在从机器读取数据并保存到文本文件中,但是一旦我将其添加为 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 

这是我的主要应用程序代码..

static void Main()
    {

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

    }

这是我使用 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)
        {
        }
    }

我使用此程序的唯一目的是通过安装程序将其作为 Windows 服务运行并启动该服务。服务启动后,它应该从机器的给定 ip 和端口读取数据并将其保存到文本文件中。我还需要这项服务来持续监控来自机器的数据,一旦新数据到达机器,它应该读取和写入文本文件。

我需要在程序中实现多线程吗?

最佳答案

系统期望 OnStart 方法及时返回(约 30 秒),因此需要将长时间运行的任务(如监控数据)移至另一个线程。这可以很简单:

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...
}

请注意,虽然您的 while (true) 循环足以让线程保持运行,但它很难在服务停止时停止它。为此,我使用 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
}

关于c# - 在 c# 中作为 Windows 服务运行时,TCP/IP 套接字不从机器读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166680/

相关文章:

c# - 使用C#访问Oracle DB时总是遇到ORA-00936缺少express

c# - ConfigurationManager 没有在 app.config 中保存值

java - 多线程 hibernate 中的未知实体

java - 通过外部网关发送 SMS 的设计评论

java - Hbase 1.0.0连接池

外部文件中的 c# razor 函数

c# - 未更新的行

node.js - 将 TCP 客户端的主机名发送到 Node JS 中的服务器

python - 从 Socket.File.Read 部分读取

ios - 使用 Socket.io 无法在两个 IOS 设备之间接收消息