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