【发布时间】:2017-08-24 14:03:40
【问题描述】:
我在 C# 中使用 winform 完成了一个应用程序,现在需要从一个自托管在 lighthttp 服务器上的网页(作为一个类包含在我的应用程序解决方案中)远程控制它(仅一些功能)。
这是服务器代码(感谢 David 的 BlogEngine):
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, for example
// "http://localhost:8080/index/".
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);
_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();
}
}
这是我的 winform 应用程序中用来打开它的代码:
WebServer ws = new WebServer(SendResponse, "http://localhost:8080/test/");
ws.Run();
这是返回给服务器的html:
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
}
当我在浏览器上打开“localhost:8080/test”时,它就像一个魅力,但是.. 我不知道如何将信息从网页传递到应用程序以在其上触发事件。
即如果我在网页上按下“关闭”按钮,它会在 winform 应用程序上触发关闭事件。
我需要实施什么来实现这个目标?
(我将根据我未来的进展逐步更新这篇文章,以使其对大家有用)
【问题讨论】:
-
您是否已经了解 Web 应用程序的工作原理?
-
@Evk 只是在理论上,从未在实践中做过。
-
那么你创建了你在默认请求中返回的html页面(在你的SendResponse中)。该 html 页面包含一个按钮,当您单击它时,您会发出另一个请求。对于此请求,您无需在 SendResponse 中返回 html,而是关闭您的表单。所以基本上你分析 HttpListenerRequest 并根据它做出不同的动作......
-
我很难想到实际需要这样做的场景。你的应用程序是什么,为什么你想要一个网页来控制它的 UI 元素?如果我正在做这样的事情,我将创建 winforms 应用程序和 Web 应用程序使用的通用程序集。
-
@RossMiller winform 应用程序用于通过套接字与另一个外部应用程序对话,发送和接收消息。我需要一个 Web UI 来控制我的应用程序的主要功能(例如发送此类消息或分析其他消息等),以便我可以通过远程工作站与之交互。它必须托管在这个自托管的 lighthttp 网络服务器上,因为我们用来执行我的应用程序的机器没有 IIS。
标签: c# .net winforms httplistener httplistenerrequest