Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在Window';s服务没有';没有反应或触发?_C#_Windows_Service_Httplistener - Fatal编程技术网

C# 为什么在Window';s服务没有';没有反应或触发?

C# 为什么在Window';s服务没有';没有反应或触发?,c#,windows,service,httplistener,C#,Windows,Service,Httplistener,我创建了两种编程代码。第一个,我只是在.NET中使用HTTPListener类。最后一个,我使用一个具有多个线程的复杂方法来处理输入的SOAP请求。对于它们,我返回SOAP响应。这些解决方案在Windows窗体应用程序中运行良好(当然,通过在单击开始按钮内移动OnStart的内容) 但是,我有一个大问题。HTTPListener的BeginGetContext似乎是安静的,不会仅仅在Windows服务中做出反应或触发。我认为这个问题不正常。这两种算法在Windows窗体应用程序中运行时没有问题。

我创建了两种编程代码。第一个,我只是在.NET中使用HTTPListener类。最后一个,我使用一个具有多个线程的复杂方法来处理输入的SOAP请求。对于它们,我返回SOAP响应。这些解决方案在Windows窗体应用程序中运行良好(当然,通过在单击开始按钮内移动OnStart的内容)

但是,我有一个大问题。HTTPListener的BeginGetContext似乎是安静的,不会仅仅在Windows服务中做出反应或触发。我认为这个问题不正常。这两种算法在Windows窗体应用程序中运行时没有问题。当然,如果启动Windows服务,Windows窗体应用程序不会同时侦听。我一次只运行其中一个

我有一个有效的自签名证书。它在Windows窗体应用程序下运行,没有问题。除了使用OnStart和OnStop之外,我对Windows服务使用相同的方法。只是在这个时候,情况才有问题

我每次都会删除并添加SSL证书,以确保已在Windows中加载证书

我更喜欢简单的编程代码。我是“保持简单”的粉丝。我不想留下任何一个。我想要最好的

你是否在生活中尝试过这种行为?我将许多应用程序从Windows窗体应用程序传输到Windows服务,过去没有任何问题

如果我执行DOS命令:“telnet localhost 30010”,Windows服务将监听通信端口30010。但是,BeginGetContext并没有像预期的那样触发我的函数ListenerCallback或ContextReady

我阅读了有关HTTPListener类的基本文档。我可以在Windows窗体应用程序环境中控制这种情况。所有方法都运行良好。这只是如果我使用Windows服务。BeginGetContext的反应与Windows服务环境中的反应不同

第一个:

public partial class SOAPServer_Service : ServiceBase {

    public string ErrorMessage = "";

    private HttpListener Listener;

    public SOAPServer_Service() {
        InitializeComponent();
    }

    protected void OnStart(string[] args) {

        try {
            this.ErrorMessage = "";

            string Port = "30010",
                   HashCertificat = "8f3146c64cb75a716a3543dfc10c2967acab9471",
                   URLEnvironment = "https://10.182.133.101:30010/WS/";

            Process ProcessusDelete = new Process();
            ProcessStartInfo StartInfoDelete = new ProcessStartInfo();
            StartInfoDelete.WindowStyle = ProcessWindowStyle.Hidden;
            StartInfoDelete.FileName = "cmd.exe";
            StartInfoDelete.Arguments = "/C C:\\Windows\\System32\\netsh http delete sslcert ipport=0.0.0.0:" + Port;
            StartInfoDelete.Verb = "runas";
            ProcessusDelete.StartInfo = StartInfoDelete;
            ProcessusDelete.Start();
            ProcessusDelete.WaitForExit(10000);
            ProcessusDelete.Close();

            Process ProcessusAdd = new Process();
            ProcessStartInfo StartInfoAdd = new ProcessStartInfo();
            StartInfoAdd.WindowStyle = ProcessWindowStyle.Hidden;
            StartInfoAdd.FileName = "cmd.exe";
            StartInfoAdd.Arguments = "/C C:\\Windows\\System32\\netsh http add sslcert ipport=0.0.0.0:" + Port + " certhash=" + HashCertificat + " appid={e2eaacd9-92e6-43cc-b51c-7a7887149607}";
            StartInfoAdd.Verb = "runas";
            ProcessusAdd.StartInfo = StartInfoAdd;
            ProcessusAdd.Start();
            ProcessusAdd.WaitForExit(10000);
            ProcessusAdd.Close();

            if (HttpListener.IsSupported) {
                if (this.Listener == null) {
                    this.Listener = new HttpListener();
                }
                this.Listener.Prefixes.Add(URLEnvironment);
                this.Listener.Start();

                // It seems to be not effective
                IAsyncResult Result = this.Listener.BeginGetContext(new AsyncCallback(this.ListenerCallback), this.Listener);
            } else {
                this.ErrorMessage = "The operating system is not up to date!";
                return false;
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_OnStart.txt", FileMode.Create)) {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
                    sw.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    protected override void OnStop() {

        try {
            this.ErrorMessage = "";

            if (this.Listener != null) {
                this.Listener.Close();
                this.Listener = null;
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_OnStop.txt", FileMode.Create)) {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
                    sw.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    private void ListenerCallback(IAsyncResult Result) {

        try {
            string SOAPRequest = "",
                   SOAPResponse = "";

            this.ErrorMessage = "";

            HttpListenerContext Context = this.Listener.EndGetContext(Result);
            HttpListenerRequest Request = Context.Request;
            HttpListenerResponse Response = Context.Response;

            if (Request.HasEntityBody) {
                Stream S = Request.InputStream;
                StreamReader SR = new StreamReader(S, Encoding.UTF8);
                SOAPRequest = SR.ReadToEnd();
                SR.Close();
                S.Close();

                using (FileStream fsIn = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Trace_Request_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".xml", FileMode.Create)) {
                    using (StreamWriter swIn = new StreamWriter(fsIn, Encoding.UTF8)) {
                        swIn.WriteLine(SOAPRequest);
                    }
                }

                //... {creation of SOAP response}

                using (FileStream fsOut = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Trace_Response_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".xml", FileMode.Create)) {
                    using (StreamWriter swOut = new StreamWriter(fsOut, Encoding.UTF8)) {
                        swOut.WriteLine(SOAPResponse);
                    }
                }

                byte[] byteSOAPResponse = UTF8Encoding.UTF8.GetBytes(SOAPResponse);

                using (Stream StreamSender = Response.OutputStream) {
                    StreamSender.Write(byteSOAPResponse, 0, byteSOAPResponse.Length);
                    StreamSender.Close();
                }

                Response.Close();

                Result = this.Listener.BeginGetContext(new AsyncCallback(this.ListenerCallback), this.Listener);
            }

        } catch (Exception E) {
            this.ErrorMessage = this.RecupereException(E);
            using (FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_ListenerCallback_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".txt", FileMode.Create)) {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
                    swEntree.WriteLine("TryCatch : ");
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }

            return;
        }
    }

    protected string RecupereException(Exception E) {
        string M = "";
        while (E != null) {
            M += E.Message;
            E = E.InnerException;
        }

        return M;
    }
}
第二个:

public partial class SOAPServer_Service : ServiceBase {

    public string ErrorMessage = "";

    private int NbrThread = 5;

    private SOAPServer_OSS ServerSOAP;

    public SOAPServer_Service() {
        InitializeComponent();

        this.ServerSOAP = new SOAPServer_OSS(this.NbrThread);
    }

    protected void OnStart(string[] args) {

        try {
            this.ServerSOAP.Start();
        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_OnStart.txt", FileMode.Create)) {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
                    sw.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    protected override void OnStop() {

        try {
            this.ServerSOAP.Stop();
        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_OnStop.txt", FileMode.Create)) {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) {
                    sw.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    protected string GetCompleteException(Exception E) {
        string M = "";
        while (E != null) {
            M += E.Message;
            E = E.InnerException;
        }

        return M;
    }
}

class SOAPServer_OSS : IDisposable {
    private readonly HttpListener listener;
    private readonly Thread listenerThread;
    private readonly Thread[] thread;
    private readonly ManualResetEvent state_listener,
                                      state_queue;
    private Queue<HttpListenerContext> queue;

    public string port = "30010",
                  hashCertificat = "8f3146c64cb75a716a3543dfc10c2967acab9471";

    public SOAPServer_OSS(int NbrThread) {

        this.thread = new Thread[NbrThread];
        this.queue = new Queue<HttpListenerContext>();
        this.state_listener = new ManualResetEvent(false);
        this.state_queue = new ManualResetEvent(false);
        this.listener = new HttpListener();
        this.listenerThread = new Thread(this.HandleRequests);

    }

    protected string GetCompleteException(Exception E) {
        string M = "";
        while (E != null) {
            M += E.Message;
            E = E.InnerException;
        }

        return M;
    }

    public void Start() {

        try {
            Process ProcessusDelete = new Process();
            ProcessStartInfo StartInfoDelete = new ProcessStartInfo();
            StartInfoDelete.WindowStyle = ProcessWindowStyle.Hidden;
            StartInfoDelete.FileName = "cmd.exe";
            StartInfoDelete.Arguments = "/C C:\\Windows\\System32\\netsh http delete sslcert ipport=0.0.0.0:" + this.port;
            StartInfoDelete.Verb = "runas";
            ProcessusDelete.StartInfo = StartInfoDelete;
            ProcessusDelete.Start();
            ProcessusDelete.WaitForExit(10000);
            ProcessusDelete.Close();

            Process ProcessusAdd = new Process();
            ProcessStartInfo StartInfoAdd = new ProcessStartInfo();
            StartInfoAdd.WindowStyle = ProcessWindowStyle.Hidden;
            StartInfoAdd.FileName = "cmd.exe";
            StartInfoAdd.Arguments = "/C C:\\Windows\\System32\\netsh http add sslcert ipport=0.0.0.0:" + this.port + " certhash=" + this.hashCertificat + " appid={e2eaacd9-92e6-43cc-b51c-7a7887149607}";
            StartInfoAdd.Verb = "runas";
            ProcessusAdd.StartInfo = StartInfoAdd;
            ProcessusAdd.Start();
            ProcessusAdd.WaitForExit(10000);
            ProcessusAdd.Close();

            this.listener.Prefixes.Add(String.Format(@"https://+:{0}/WS/", this.port));
            this.listener.Start();
            this.listenerThread.Start();

            for (int i = 0; i < this.thread.Length; i++) {
                this.thread[i] = new Thread(this.Worker);
                this.thread[i].Name = "Thread_" + (i + 1).ToString();
                this.thread[i].Start();
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_SOAPServer_Start.txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    public void Dispose() { this.Stop(); }

    public void Stop() {

        try {
            this.state_listener.Set();
            this.listenerThread.Join();
            foreach (Thread T in this.thread) {
                T.Join();
            }
            this.listener.Stop();

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_Stop.txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    private void HandleRequests() {

        try {
            while (this.listener.IsListening) {
                // It seems to be not effective
                var context = this.listener.BeginGetContext(this.ContextReady, null);
                WaitHandle[] wait = new[] { this.state_listener, context.AsyncWaitHandle };
                if (0 == WaitHandle.WaitAny(wait)) {
                    return;
                }
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_HandleRequests.txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    private void ContextReady(IAsyncResult ar) {

        try {
            lock (this.queue) {
                this.queue.Enqueue(this.listener.EndGetContext(ar));
                this.state_queue.Set();
            }
        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_ContextReady.txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    private void Worker() {

        try {
            WaitHandle[] wait = new[] { this.state_queue, this.state_listener };
            while (0 == WaitHandle.WaitAny(wait)) {
                HttpListenerContext context;
                lock (this.queue) {
                    if (this.queue.Count > 0) {
                        context = this.queue.Dequeue();
                    } else {
                        this.state_queue.Reset();
                        continue;
                    }
                }

                this.ProcessRequest(context);
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_Worker.txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }

    private void ProcessRequest(HttpListenerContext Contexte) {

        try {
            HttpListenerRequest Request = Contexte.Request;
            HttpListenerResponse Response = Contexte.Response;

            if (Request.HasEntityBody) {
                Stream S = Request.InputStream;
                StreamReader SR = new StreamReader(S, Encoding.UTF8);
                SOAPRequest = SR.ReadToEnd();
                SR.Close();
                S.Close();

                using (FileStream fsIn = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Trace_Request_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".xml", FileMode.Create)) {
                    using (StreamWriter swIn = new StreamWriter(fsIn, Encoding.UTF8)) {
                        swIn.WriteLine(SOAPRequest);
                    }
                }

                //... {creation of SOAP response}

                using (FileStream fsOut = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Trace_Response_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".xml", FileMode.Create)) {
                    using (StreamWriter swOut = new StreamWriter(fsOut, Encoding.UTF8)) {
                        swOut.WriteLine(SOAPResponse);
                    }
                }

                byte[] byteSOAPResponse = UTF8Encoding.UTF8.GetBytes(SOAPResponse);

                using (Stream StreamSender = Response.OutputStream) {
                    StreamSender.Write(byteSOAPResponse, 0, byteSOAPResponse.Length);
                    StreamSender.Close();
                }

                Response.Close();
            }

        } catch (Exception E) {
            this.ErrorMessage = this.GetCompleteException(E);
            using (FileStream fsEntree = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Exception_ProcessRequest_" + DateTime.Now.ToString("s").Replace("/", "").Replace("-", "").Replace(":", "") + ".txt", FileMode.Create)) {
                using (StreamWriter swEntree = new StreamWriter(fsEntree, Encoding.UTF8)) {
                    swEntree.WriteLine("TryCatch : ");
                    swEntree.WriteLine(this.ErrorMessage);
                }
            }
        }
    }
}
public部分类SOAPServer\u服务:ServiceBase{
公共字符串ErrorMessage=“”;
私有线程=5;
私有SOAPServer\u OSS ServerSOAP;
公共SOAPServer_服务(){
初始化组件();
this.ServerSOAP=新的SOAPServer_OSS(this.nbr线程);
}
受保护的void OnStart(字符串[]args){
试一试{
这是.ServerSOAP.Start();
}捕获(例外E){
this.ErrorMessage=this.GetCompleteException(E);
使用(FileStream fs=newfilestream(Path.GetDirectoryName(System.Reflection.Assembly.getExecutionGassembly().Location)+“\\Exception\u OnStart.txt”,FileMode.Create)){
使用(StreamWriter sw=新StreamWriter(fs,Encoding.UTF8)){
sw.WriteLine(此错误消息);
}
}
}
}
受保护的覆盖void OnStop(){
试一试{
this.ServerSOAP.Stop();
}捕获(例外E){
this.ErrorMessage=this.GetCompleteException(E);
使用(FileStream fs=newfilestream(Path.GetDirectoryName(System.Reflection.Assembly.getExecutionGassembly().Location)+“\\Exception\u OnStop.txt”,FileMode.Create)){
使用(StreamWriter sw=新StreamWriter(fs,Encoding.UTF8)){
sw.WriteLine(此错误消息);
}
}
}
}
受保护字符串GetCompleteException(异常E){
字符串M=”“;
while(E!=null){
M+=E.信息;
E=E.InnerException;
}
返回M;
}
}
类SOAPServer_OSS:IDisposable{
私有只读HttpListener侦听器;
私有只读线程listenerThread;
私有只读线程[]线程;
专用只读手册重置事件状态\u侦听器,
状态队列;
专用队列;
公共字符串端口=“30010”,
hashCertificate=“8f3146c64cb75a716a3543dfc10c2967acab9471”;
公共SOAPServer_OSS(int-nbr线程){
this.thread=新线程[NBR线程];
this.queue=新队列();
this.state_listener=new ManualResetEvent(false);
this.state_queue=new ManualResetEvent(false);
this.listener=新的HttpListener();
this.listenerThread=新线程(this.HandleRequests);
}
受保护字符串GetCompleteException(异常E){
字符串M=”“;
while(E!=null){
M+=E.信息;
E=E.InnerException;
}
返回M;
}
公开作废开始(){
试一试{
Process ProcessusDelete=新流程();
ProcessStartInfo StartInfoDelete=新的ProcessStartInfo();
StartInfoDelete.WindowStyle=ProcessWindowStyle.Hidden;
StartInfoDelete.FileName=“cmd.exe”;
StartInfoDelete.Arguments=“/C:\\Windows\\System32\\netsh http delete sslcert ipport=0.0.0:”+this.port;
StartInfoDelete.Verb=“runas”;
ProcessusDelete.StartInfo=StartInfoDelete;
ProcessusDelete.Start();
流程USDelete.WaitForExit(10000);
ProcessusDelete.Close();
Process ProcessusAdd=新流程();
ProcessStartInfo StartInfoAdd=新的ProcessStartInfo();
StartInfoAdd.WindowStyle=ProcessWindowStyle.Hidden;
StartInfoAdd.FileName=“cmd.exe”;
StartInfoAdd.Arguments=“/C:\\Windows\\System32\\netsh http add sslcert ipport=0.0.0:“+this.port+”certhash=“+this.hashCertificate+”appid={e2eaacd9-92e6-43cc-b51c-7a787149607}”;
StartInfoAdd.Verb=“runas”;
ProcessusAdd.StartInfo=StartInfoAdd;
ProcessusAdd.Start();
过程ADD.WaitForExit(10000);
ProcessusAdd.Close();
this.listener.Prefixes.Add(String.Format)(@“https:/