Web服务器学习记录

使用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博客

C# Windows Service中使用Signalr开启服务时候报System.Net.HttpListenerException:拒绝访问解决方法_system.net.httplistenerexception:“拒绝访问。”-CSDN博客

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值