简体   繁体   中英

Windows service webs server cannot connect to other machines

I am attempting to design a windows service that contains a web server to do basic get request handling. Requests from the localhost work just find but I am unable to process requests from other machines. On python, setting the IP address to 0.0.0.0 allows the server to process requests from any IP on the network. I have found examples that use http://*:port/ or http://+:port/ to obtain this functionality in C# but these have not worked for me.

I am currently starting a HttpListener ( WebServer.cs ) when the windows service ( UsherService.cs ) receives its start command. If there is a better way to do this, I'd appreciate that answer as well.

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

}

The firewall was blocking the localhost from communicating to other devices on the network. I had to allow for communication over that port

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM