使用winform构建web服务器,
参考代码:使用Winform构建Web服务器 (winform web服务器)-技术文档-服务器优惠导航-AB资源网 (xxab.cn)
C# winform 请求http(IT技术) (qb5200.com)
微软的文档链接:
HttpListenerRequest 类 (System.Net) | Microsoft Learn
参考后写的测试代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class SimpleWebServer
{
public static void Start()
{
var listener = new HttpListener();
listener.Prefixes.Add("http://192.168.1.19:8082/");
listener.Start();
while (true)
{
var context = listener.GetContext();
var response = context.Response;
response.StatusCode = 200;
Console.WriteLine("接受请求Url:" + context.Request.Url.ToString());
Console.WriteLine("接受请求Method=:" + context.Request.HttpMethod.ToString());
Console.WriteLine("接受请求的客户端地址=:" + context.Request.RemoteEndPoint.ToString());
if (context.Request.Url.AbsoluteUri == "http://192.168.1.19:8082/t.txt" && context.Request.HttpMethod == "GET")
{
string filePath = @"C:\UserWorkspace\testGhf.txt";
var buffer = File.ReadAllBytes(filePath); // 读取文件内容到字节数组
context.Response.ContentType = "application/octet-stream"; // 设置响应类型为二进制流
context.Response.OutputStream.Write(buffer, 0, buffer.Length); // 写入文件内容到响应流
response.Close();
}
else
{
var html = "Hello,World ghf " + System.DateTime.Now.ToString();
var buffer1 = System.Text.Encoding.UTF8.GetBytes(html);
response.OutputStream.Write(buffer1, 0, buffer1.Length);
response.Close();
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
SimpleWebServer.Start();
}
会遇到启动失败,修改防火墙和入站规则:
C# System.Net.HttpListenerException:“拒绝访问”
例如:
C# System.Net.HttpListenerException:“拒绝访问”_system.net.httplistenerexception:“拒绝访问。”-CSDN博客