1. 库类:

\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\System.dll
System.Net.HttpListener

2. 代码

2.1 服务端

class Program
{
static HttpListener httpobj;
static void Main(string[] args)
{
//提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
httpobj = new HttpListener();
//定义url及端口号,通常设置为配置文件
httpobj.Prefixes.Add("http://127.0.0.1:8080/");
//启动监听器
httpobj.Start();
//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
httpobj.BeginGetContext(Result, null);
Console.WriteLine($"服务端初始化完毕,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");
Console.ReadKey();
} private static void Result(IAsyncResult ar)
{
//当接收到请求后程序流会走到这里 //继续异步监听
httpobj.BeginGetContext(Result, null);
var guid = Guid.NewGuid().ToString();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"接到新的请求:{guid},时间:{DateTime.Now.ToString()}");
//获得context对象
var context = httpobj.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 returnObj = null;//定义返回客户端的信息
if (request.HttpMethod == "POST" && request.InputStream != null)
{
//处理客户端发送的请求并返回处理信息
returnObj = HandleRequest(request, response);
}
else
{
returnObj = $"不是post请求或者传过来的数据为空";
}
var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
try
{
using (var stream = response.OutputStream)
{
//把处理信息返回到客户端
stream.Write(returnByteArr, 0, returnByteArr.Length);
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"网络蹦了:{ex.ToString()}");
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"请求处理完成:{guid},时间:{ DateTime.Now.ToString()}\r\n");
} private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
{
string data = null;
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可以进行其他操作
}
catch (Exception ex)
{
response.StatusDescription = "404";
response.StatusCode = 404;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考
}
response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"接收数据完成:{data.Trim()},时间:{DateTime.Now.ToString()}");
return $"接收数据完成";
}
}

2.2 请求端:

static void Main(string[] args)
{
string operation;
do
{
Console.WriteLine("按任意键发送数据到服务端");
Console.ReadLine();
var wc = new WebClient();
var url = "http://127.0.0.1:8080";
Console.WriteLine($"请求服务地址:{url},时间:{DateTime.Now.ToString()}");
//模拟一个json数据发送到服务端
var data = new Data(1, "张三");
var jsonModel = JsonConvert.SerializeObject(data);
//发送到服务端并获得返回值
var returnInfo = wc.UploadData(url, Encoding.UTF8.GetBytes(jsonModel));
//把服务端返回的信息转成字符串
var str = Encoding.UTF8.GetString(returnInfo);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"服务端返回信息:{str},时间:{DateTime.Now.ToString()}");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"请问是否继续:继续 【y】,退出【n】");
operation = Console.ReadLine();
} while (operation == "y");
} class Data
{
public Data(int id, string name)
{
this.ID = id;
this.Name = name;
}
public int ID { get; set; } public string Name { get; set; }
}

3. Http 系列

3.1 发起请求

使用 HttpWebRequest 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501036.html

使用 WebClient 发起 Http 请求 :https://www.cnblogs.com/MichaelLoveSna/p/14501582.html

使用 HttpClient 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501592.html

使用 HttpClient 发起上传文件、下载文件请求:https://www.cnblogs.com/MichaelLoveSna/p/14501603.html

3.2 接受请求

使用 HttpListener 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501628.html

使用 WepApp 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501612.html

使用 WepApp 处理文件上传、下载请求:https://www.cnblogs.com/MichaelLoveSna/p/14501616.html

C# 应用 - 使用 HttpListener 接受 Http 请求的更多相关文章

  1. C# 应用 - 使用 WepApp 接受 Http 请求

    库类: Owin.dll Owin.IAppBuilder Microsoft.Owin.dll Microsoft.Owin.OwinContext Microsoft.Owin.Hosting.d ...

  2. Web APi之捕获请求原始内容的实现方法以及接受POST请求多个参数多种解决方案(十四)

    前言 我们知道在Web APi中捕获原始请求的内容是肯定是很容易的,但是这句话并不是完全正确,前面我们是不是讨论过,在Web APi中,如果对于字符串发出非Get请求我们则会出错,为何?因为Web A ...

  3. 限制action所接受的请求方式或请求参数

    原文:http://www.cnblogs.com/liukemng/p/3726897.html 2.限制action所接受的请求方式(get或post): 之前我们在HelloWorldContr ...

  4. Controller 的 Action 只接受 Ajax 请求

    ASP.NET MVC 使 Controller 的 Action 只接受 Ajax 请求. 2014-08-27 14:19 by h82258652, 555 阅读, 2 评论, 收藏, 编辑 首 ...

  5. C# 发送和接受Get请求

    1.发送Get请求 public static string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (H ...

  6. C#发送和接受POST请求

    1.发送Post请求代码 /// <summary> /// 发起Http请求 /// </summary> /// <param name="flightDa ...

  7. Spring MVC 接受的请求参数

    目录 1. 概述 2. 详解 2.1 处理查询参数 2.2 处理路径参数接受输入 2.3 处理表单 3. 补充内容 3.1 Ajax/JSON 输入 3.2 multipart参数 3.3 接收 he ...

  8. 让webapi只接受ajax请求

    为了测试先做一个简单的webapi,直接用新建项目时默认的就可以了.   在浏览器中测试request get,得到结果   然后再项目中新建一个AjaxOnly的类   AjaxOnly继承Acti ...

  9. ASP.NET MVC 使 Controller 的 Action 只接受 Ajax 请求。

    首先,ajax 请求跟一般的 web 请求本质是相同的,都是 http 请求.理论上服务器端是无法区分该次请求是不是 ajax 请求的,但是,既然标题都已经说了,那么肯定是有办法做的. 在 ajax ...

随机推荐

  1. HTTP笔记2--简单的HTTP 协议

    HTTP概念 HTTP用于客户端和服务器之间的通信 客户端:请求访问文本或图像等资源的一端 服务器端而提供资源响应的一端 通过请求和响应的交换达成通信 HTTP 协议规定,请求从客户端发出,最后服务器 ...

  2. k8s二进制部署 - dashboard安装

    配置资源清单rbac.yaml apiVersion: v1 kind: ServiceAccount metadata: labels: k8s-app: kubernetes-dashboard ...

  3. NFS 共享存储

    目录 环境准备 NFS服务端 NFS客户端 部署时常见报错 httpd服务 NFS 共享存储的坑 环境准备 主机名 WanIP(Wide Area Network) LanIP(Local Area ...

  4. bitbar 网站攻击实验

    实验环境 https://github.com/TouwaErioH/security/tree/master/web1 Windows10 Oracle VM VirtualBox Ubuntu16 ...

  5. unbuntu 安装 bochs

    参考 https://www.cnblogs.com/HonkerYblogs/p/10285619.html https://blog.csdn.net/time4/article/details/ ...

  6. SpringBoot 全局视角看springboot

    从单体架构到微服务 单体架构 任何一个网站在发布初期几乎都不可能立马就拥有庞大的用户流量和海量数据,都是在不停 的试错过程中一步一步演变其自身架构,满足其自身业务.比如现在能够抗住双十一这么大 流量的 ...

  7. Linux错误记录贴

    add-apt-repository 不要写成 add-apt-repository service  不要写成 sevice 总之在打命令的时候要注意不要拼错单词 对于ls命令权限不够我们可以先su ...

  8. Express All In One

    Express All In One express.js, node.js web framework # v4.17.1 Latest, on May 26, 2019 $ yarn add ex ...

  9. Objective C & Swift & iOS & App

    Objective C & Swift & iOS & App https://www.runoob.com/ios/ios-objective-c.html https:// ...

  10. 为什么ElasticSearch比MySQL更适合全文索引

    熟悉 MySQL 的同学一定都知道,MySQL 对于复杂条件查询的支持并不好.MySQL 最多使用一个条件涉及的索引来过滤,然后剩余的条件只能在遍历行过程中进行内存过滤,对这个过程不了解的同学可以先行 ...