c# HttpListener 使用
2024-09-06 03:24:47
与 IIS 上发布网站相比,使用 HttpListener 编程的程序更加轻量化,易于发布和更新。配合 Thread 或 Task 类也可满足一定的并发。
https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
using System.IO;
//https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2 namespace WebServer
{
class Program
{
static void Main(string[] args)
{
try
{
using (HttpListener listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:8888/");
listener.Start();
Console.WriteLine("开始监听");
while (true)
{
try
{
HttpListenerContext context = listener.GetContext();//阻塞
HttpListenerRequest request = context.Request;
string postData = new StreamReader(request.InputStream).ReadToEnd();
Console.WriteLine("收到请求:" + postData);
HttpListenerResponse response = context.Response;//响应
string responseBody = "响应";
response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody);
response.ContentType = "text/html; Charset=UTF-8";
//输出响应内容
Stream output = response.OutputStream;
using (StreamWriter sw = new StreamWriter(output))
{
sw.Write(responseBody);
}
Console.WriteLine("响应结束");
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
}
}
catch (Exception err)
{
Console.WriteLine("程序异常,请重新打开程序:" + err.Message);
}
}
}
}
最新文章
- Programming in Lua读书笔记
- %1 不是有效的Win32应用程序
- 数据结构和算法 – 4.字符串、 String 类和 StringBuilder 类
- Delphi运算符总结
- Eclemma各种安装方式以及安装失败解决
- S3c6410 平台 Android系统的Wi-Fi调试记录
- 【leetcode】Word Break (middle)
- 10 steps to get Ruby on Rails running on Windows with IIS FastCGI- 摘自网络
- 获取文本区域(textarea)行数【换行获取输入用户名个数】
- 各种Adapter的用法
- 关于JAVA Project.waitfor()返回值是1
- JS通用方法扩展
- Arduino中hex文件的保存及应用(转)
- Maven进阶宝典
- iOS XIB等比例适配
- Navicat 提示 Access violation at address ***(如004ECCF4) in module ‘navicat.exe’. Read of address ***(如00000048)
- 201621123075 week06-接口、内部类
- TVTK安装
- Es6入门解构
- Django admin 产生'WSGIRequest' object has no attribute 'user'的错误