监听HTTP请求的对象
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ECS_S_RFID
{
public class ComHttpServer
{
/// <summary>
/// 当前监听HTTP请求的对象
/// </summary>
private HttpListener currentListener;
/// <summary>
/// 初始化时指定一个要监听的网络地址,以'/'结尾
/// 例如:"http://192.168.2.181:8080/index/".
/// </summary>
/// <param name="url">要监听的网络地址</param>
public ComHttpServer(string url)
{
this.currentListener = new HttpListener();
this.currentListener.Prefixes.Add(url);
}
/// <summary>
/// 初始化时指定多个地址,同时监听,地址以'/'结束
/// 例如:"http://192.168.2.181:8080/index/".
/// </summary>
/// <param name="urls">要监听的网络地址集合</param>
public ComHttpServer(string[] urls)
{
this.currentListener = new HttpListener();
foreach (string s in urls)
{
this.currentListener.Prefixes.Add(s);
}
}
/// <summary>
/// 监听HTTP请求
/// </summary>
public void StartListen()
{
if (!HttpListener.IsSupported)
{
return;
}
////开始监听
this.currentListener.Start();
this.currentListener.BeginGetContext(Result, null);
}
/// <summary>
/// 处理接受消息的委托
/// </summary>
public Action<string,string> HandleRecMsg { get; set; }
private void Result(IAsyncResult ar)
{
//当接收到请求后程序流会走到这里
//继续异步监听
currentListener.BeginGetContext(Result, null);
//Console.ForegroundColor = ConsoleColor.White;
//获得context对象
var context = currentListener.EndGetContext(ar);
var request = context.Request;
var response = context.Response;
////如果是js的ajax请求,还可以设置跨域的ip地址与参数
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件
//context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件
context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件
context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
context.Response.ContentEncoding = Encoding.UTF8;
string rep = "OK";//定义返回客户端的信息
if (request.HttpMethod == "POST" && request.InputStream != null)
{
//处理客户端发送的请求并返回处理信息
rep = HandleRequest(request, response);
}
else
{
}
var returnByteArr = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(rep));//设置客户端返回信息的编码
try
{
using (var stream = response.OutputStream)
{
//把处理信息返回到客户端
stream.Write(returnByteArr, 0, returnByteArr.Length);
}
}
catch (Exception ex)
{
}
}
private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
{
string data = null;
string rep = "OK";
try
{
var byteList = new List<byte>();
var byteArr = new byte[2048];
int readLen = 0;
int len = 0;
//接收客户端传过来的数据并转成字符串类型
do
{
readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
len += readLen;
byteList.AddRange(byteArr);
} while (readLen != 0);
data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);
//获取得到数据data可以进行其他操作
string method = request.Url.PathAndQuery.Replace("//", "").Replace("/","");
HandleRecMsg?.Invoke(method,data);
}
catch (Exception ex)
{
response.StatusDescription = "404";
response.StatusCode = 404;
return rep;
}
response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
return rep;
}
/// <summary>
/// 结束监听
/// </summary>
public void EndListen()
{
this.currentListener.Abort();
}
}
}
其它页面引用
ComHttpServer cs = new ComHttpServer("http://192.168.2.54:8080/");
cs.HandleRecMsg = new Action<string, string>((method,msg) => {
//msg
});
cs.StartListen();

浙公网安备 33010602011771号