通过 c# 服务发送服务器时间作为对 HTTP GET 的响应

本文关键字:HTTP GET 响应 时间 服务 服务器 通过 | 更新日期: 2023-09-27 18:33:53

好吧,我想我现在 100% 工作了!这是代码,欢迎任何批评,这是我第一次尝试 c#,主要来自 JS 背景。最终使用了thread.abort,不确定这是否是结束这种情况的最佳方法。我也输入了一个_shouldStop布尔值。

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();
    }
}

通过 c# 服务发送服务器时间作为对 HTTP GET 的响应

您可以在

HTTPListener请求方法中使用的东西。

public void HttpListenerCallback(IAsyncResult result)
{
    HttpListener listener = (HttpListener)result.AsyncState;
    HttpListenerContext context = listener.EndGetContext(result);
    HttpListenerResponse Response = context.Response;
    String dateAsString = DateTime.Now.ToString(@"MM'/dd'/yyyy h':mm tt");
    byte[] bOutput = System.Text.Encoding.UTF8.GetBytes(dateAsString);
    Response.ContentType = "text/plain";
    Response.ContentLength64 = bOutput.Length;
    Stream OutputStream = Response.OutputStream;
    OutputStream.Write(bOutput, 0, bOutput.Length);
    OutputStream.Close();
}

为此,您应该在异步(非阻塞)模式下使用 HTTPListener。前任:

public void NonblockingListener()
{
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://*:8081/");
    listener.Start();
    IAsyncResult result = listener.BeginGetContext(
        new AsyncCallback(HttpListenerCallback), listener);
    Console.WriteLine("Waiting for request to be processed asyncronously.");
    result.AsyncWaitHandle.WaitOne(); //just needed to don't close this thread, you can do other work or run in a loop
    Console.WriteLine("Request processed asyncronously.");
    listener.Close();
}

更多信息: http://msdn.microsoft.com/en-us//library/system.net.httplistener.aspx