尝试实现UDP Windows服务时,循环未运行

时间:2013-12-09 15:30:48

标签: c# windows-services

我正在尝试编写Windows服务以通过UDP端口接收数据。 (该程序作为独立的Windows控制台应用程序工作)。 DoWork()方法包含等待数据通过UDP的循环,但是日志文件AuthService.txt永远不会从DoWork方法更新。有任何想法吗??感谢

class AccessControlService : ServiceBase
{
    static void Main()
    {
        System.ServiceProcess.ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new AccessControlService() };
        ServiceBase.Run(ServicesToRun);
    }

    public void InitilizeComponent()
    {
        this.ServiceName = "ACS";
    }

    private string folderPath = @"C:\Temp\";

    protected override void OnStart(string[] args)
    {
        if (!System.IO.Directory.Exists(folderPath))
            System.IO.Directory.CreateDirectory(folderPath);

        FileStream fs = new FileStream(folderPath + "\\AuthService.txt",
            FileMode.OpenOrCreate, FileAccess.Write);

        StreamWriter m_streamwriter = new StreamWriter(fs);
        m_streamwriter.BaseStream.Seek(0, SeekOrigin.End);
        m_streamwriter.WriteLine("Access control service started at " + 
            DateTime.Now.ToShortDateString() + " " + 
            DateTime.Now.ToShortTimeString() + "\n");
        m_streamwriter.Flush();
        m_streamwriter.Close();

        DoWork();
    }

    protected override void OnStop()
    {
        FileStream fs = new FileStream(folderPath + "\\AuthService.txt",
            FileMode.OpenOrCreate, FileAccess.Write);

        StreamWriter m_streamwriter = new StreamWriter(fs);
        m_streamwriter.BaseStream.Seek(0, SeekOrigin.End);
        m_streamwriter.WriteLine("Access control service stopped at " + 
            DateTime.Now.ToShortDateString() + " " + 
            DateTime.Now.ToShortTimeString() + "\n");
        m_streamwriter.Flush();
        m_streamwriter.Close();
    }

    private void InitializeComponent()
    {
        // 
        // AccessControlService
        // 
        this.ServiceName = "AccessControlService";
    }

    private void DoWork()
    {
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8888);
        UdpClient newsock = new UdpClient(ipep);

        Console.WriteLine("Waiting for a client to connect on port 8888...");

        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

        while (true)
        {
            data = newsock.Receive(ref sender);

            FileStream fs = new FileStream(folderPath + "\\AuthService.txt",
            FileMode.OpenOrCreate, FileAccess.Write);

            StreamWriter m_streamwriter = new StreamWriter(fs);
            m_streamwriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamwriter.WriteLine("UDP Data received");
            m_streamwriter.Flush();
            m_streamwriter.Close();
        }
    }
}

0 个答案:

没有答案