Windows服务Web服务器无法连接到其他计算机

时间:2018-01-15 17:58:08

标签: c# windows-services web-development-server

我正在尝试设计一个包含Web服务器的Windows服务来执行基本的get请求处理。来自localhost工作的请求只是找到但我无法处理来自其他计算机的请求。在python上,将IP地址设置为0.0.0.0允许服务器处理来自网络上任何IP的请求。我找到了使用http://*:port/http://+:port/在C#中获取此功能的示例,但这些对我没有用。

当Windows服务(HttpListener)收到启动命令时,我正在启动WebServer.csUsherService.cs)。如果有更好的方法可以做到这一点,我也会很感激。

Program.cs的

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace UsherService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new UsherService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

UsherService.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace UsherService
{
    public partial class UsherService : ServiceBase
    {

        WebServer ws;

        public UsherService()
        {
            InitializeComponent();

        }

        public static string SendResponse(HttpListenerRequest request)
        {
            return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                ws = new WebServer(SendResponse, "http://*:5000/");
                ws.Run();
                System.IO.File.AppendAllText(@"C:\Users\kburd\Desktop\WriteText.txt", "Started Successfully");
            }
            catch(Exception e)
            {
                System.IO.File.AppendAllText(@"C:\Users\kburd\Desktop\WriteText.txt", e.Message);
            }




        }

        protected override void OnStop()
        {

            System.IO.File.AppendAllText(@"C:\Users\kburd\Desktop\WriteText.txt", "Stopped Successfully");

        }
    }
}

WebServer.cs

using System;
using System.Net;
using System.Text;
using System.Threading;

public class WebServer
{

    private readonly HttpListener _listener = new HttpListener();
    private readonly Func<HttpListenerRequest, string> _responderMethod;

    public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
    {

        if (!HttpListener.IsSupported)
            throw new NotSupportedException(
                "Needs Windows XP SP2, Server 2003 or later.");

        // URI prefixes are required
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");

        // A responder method is required
        if (method == null)
            throw new ArgumentException("method");

        foreach (string s in prefixes)
        {
            _listener.Prefixes.Add(s);
            System.IO.File.AppendAllText(@"C:\Users\kburd\Desktop\WriteText2.txt", s);
        }

        _responderMethod = method;
        _listener.Start();

    }

    public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }

    public void Run()
    {
        ThreadPool.QueueUserWorkItem((o) =>
        {
            Console.WriteLine("Webserver running...");
            try
            {
                while (_listener.IsListening)
                {
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        var ctx = c as HttpListenerContext;
                        try
                        {
                            string rstr = _responderMethod(ctx.Request);
                            byte[] buf = Encoding.UTF8.GetBytes(rstr);
                            ctx.Response.ContentLength64 = buf.Length;
                            ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                        }
                        catch { } // suppress any exceptions
                        finally
                        {
                            // always close the stream
                            ctx.Response.OutputStream.Close();
                        }
                    }, _listener.GetContext());
                }
            }
            catch { } // suppress any exceptions
        });
    }

    public void Stop()
    {
        _listener.Stop();
        _listener.Close();
    }

}

1 个答案:

答案 0 :(得分:0)

防火墙阻止localhost与网络上的其他设备通信。我不得不允许通过该端口进行通信