与 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);
}
}
}
}

最新文章

  1. Programming in Lua读书笔记
  2. %1 不是有效的Win32应用程序
  3. 数据结构和算法 – 4.字符串、 String 类和 StringBuilder 类
  4. Delphi运算符总结
  5. Eclemma各种安装方式以及安装失败解决
  6. S3c6410 平台 Android系统的Wi-Fi调试记录
  7. 【leetcode】Word Break (middle)
  8. 10 steps to get Ruby on Rails running on Windows with IIS FastCGI- 摘自网络
  9. 获取文本区域(textarea)行数【换行获取输入用户名个数】
  10. 各种Adapter的用法
  11. 关于JAVA Project.waitfor()返回值是1
  12. JS通用方法扩展
  13. Arduino中hex文件的保存及应用(转)
  14. Maven进阶宝典
  15. iOS XIB等比例适配
  16. Navicat 提示 Access violation at address ***(如004ECCF4) in module ‘navicat.exe’. Read of address ***(如00000048)
  17. 201621123075 week06-接口、内部类
  18. TVTK安装
  19. Es6入门解构
  20. Django admin 产生'WSGIRequest' object has no attribute 'user'的错误

热门文章

  1. AI-Tensorflow-神经网络优化算法-梯度下降算法-学习率
  2. Mac版Navicat Premium激活教程
  3. c#同时验证手机号和座机号正则
  4. python关键字global和nonlocal总结
  5. Java面向对象的特征与含义
  6. (ACM模板)不定长数组vector
  7. 系统调用system_call处理过程
  8. Ubuntu简单安装kafka及使用
  9. bzoj 1001 原图最小割转化为对偶图最短路
  10. apache You don't have permission to access / on this server.无权访问