0

よし、今は 100% 動作していると思います! これがコードです。批評は大歓迎です。これは、主にJSのバックグラウンドから来て、C#での最初の試みでした。thread.abort を使用して終了しましたが、それがこれを終了する最善の方法であるかどうかはわかりません。_shouldStop bool も入れました。

public partial class TimeReporterService : ServiceBase
{
    private Thread worker = null;
    private bool _shouldStop = false;

    public TimeReporterService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _shouldStop = false;
        worker = new Thread(SimpleListenerExample);
        worker.Name = "Time Reporter";
        worker.IsBackground = false;
        worker.Start();
    }

    protected override void OnStop()
    {
        _shouldStop = true;
        worker.Abort();
    }

    void SimpleListenerExample()
    {
        string[] prefixes = new[] { "http://*:12227/" };
        // URI prefixes are required, 
        // for example "http://contoso.com:8080/index/".
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");

        // Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes. 
        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
        }
        listener.Start();
        while (!_shouldStop)
        {
            // Note: The GetContext method blocks while waiting for a request. 
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Construct a response. 
            string responseString = "{\"systemtime\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
        listener.Stop();
    }
}
4

1 に答える 1