写C#少说也有10来年了. 竟然可以在winform中这样开启Http服务, 以后可以不要iis了.
代码摘抄自AIBOX的Demo
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AiBox.Win.Server.Demo
{
public class WebPostService
{
private static WebPostService _instance;
public static WebPostService Instance
{
get
{
if (_instance == null)
{
_instance = new WebPostService();
}
return _instance;
}
}
private System.Net.HttpListener _listener = null;
public bool startSta = false;
/// <summary>
/// 启动
/// </summary>
public void Start(string ip,int port)
{
Stop();
List<string> httpPrefixes = new List<string>();
httpPrefixes.Add("http://" + ip + ":" + port + "/" + "UpVmsRecord/");
new Thread(new ThreadStart(delegate
{
_listener = new HttpListener();
while (true)
{
try
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
//_listener.Prefixes.Add(httpPrefixes0);
//_listener.Prefixes.Add(httpPrefixes1);
if (httpPrefixes != null)
{
foreach (string url in httpPrefixes)
{
_listener.Prefixes.Add(url);
}
}
_listener.Start();
}
catch (Exception ex)
{
startSta = false;
break;
}
//线程池
int minThreadNum;
int portThreadNum;
int maxThreadNum;
ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
//ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);
try
{
while (true)
{
startSta = true;
//等待请求连接
//没有请求则GetContext处于阻塞状态
HttpListenerContext ctx = _listener.GetContext();
ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
}
}
catch {
startSta = false;
}
}
})).Start();
}
/// <summary>
/// 停止
/// </summary>
public void Stop()
{
if (_listener != null)
{
_listener.Stop();
_listener.Close();
_listener = null;
}
}
/// <summary>
/// 任务进
/// </summary>
/// <param name="obj"></param>
void TaskProc(object obj)
{
HttpListenerContext ctx = (HttpListenerContext)obj;
try
{
var url = ctx.Request.Url.AbsoluteUri;
Stream stream = ctx.Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
if (url.Contains("UpVmsRecord"))
{
#region
string body = reader.ReadToEnd();
//这里的body就是客户端发过来的数据
var upRecord = Newtonsoft.Json.JsonConvert.DeserializeObject<UpEventRecord>(body);
if(upRecord!=null)
{
Form1._Instance.InsertRecord(upRecord);
}
#endregion
}
stream.Close();
ctx.Response.Close();
ctx = null;
}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}
}
这篇文章介绍了一种使用C#在Windows Forms应用程序中实现简易HTTP服务的方法,无需借助IIS,通过`HttpListener`实现在指定IP和端口上监听并处理POST请求的示例。
869





