C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#热重载

C# .NET基于PicoServer的Live Reload实现热重载的完整方案

作者:桔子雨

这篇文章主要为大家详细介绍了如何基于.NET实现的零配置热重载服务器,通过文件监控、防抖处理及WebSocket广播等步实现热重载,文中的示例代码讲解详细,有需要的可以了解下

.NET 是一个开源、跨平台的开发平台,运行稳定,资源消耗低,AOT 编译进一步降低了交付体积。本文基于 .NET 10 实现一个零配置的热重载服务器,核心代码不到 50 行。

依赖安装:dotnet add package PicoServer

一、热重载的本质

热重载解决的问题:文件保存后浏览器自动刷新

核心流程:文件变更 → 服务端检测 → WebSocket 推送 → 浏览器刷新

二、实现

2.1 文件监控与防抖

using PicoServer;
using System.Timers;
using System.IO;

string staticRoot = "wwwroot";
var app = new WebAPIServer();

var watcher = new FileSystemWatcher(staticRoot)
{
    EnableRaisingEvents = true,
    IncludeSubdirectories = true
};

var timer = new System.Timers.Timer(200) { AutoReset = false };
timer.Elapsed += async (_, _) => await app.WsBroadcastAsync("reload");

void OnChange(object s, FileSystemEventArgs e)
{
    var name = Path.GetFileName(e.Name);
    if (string.IsNullOrEmpty(name) || name.StartsWith('.') || name.StartsWith('~'))
        return;  // 过滤 IDE 临时文件
    
    timer.Stop();
    timer.Start();  // 200ms 内无新事件才触发
}

watcher.Changed += OnChange;
watcher.Created += OnChange;
watcher.Deleted += OnChange;
watcher.Renamed += OnChange;

防抖的必要性:一次保存操作可能触发 Changed、Created、Renamed 多个事件,防抖将其合并为一次广播,避免页面重复刷新。

2.2 WebSocket 广播

app.enableWebSocket = true;
app.WsOnConnectionChanged = (_, _) => Task.CompletedTask;

PicoServer 开启 WebSocket 后,通过以下方法广播:

await app.WsBroadcastAsync("reload");

2.3 客户端脚本注入

在返回 HTML 时自动注入 WebSocket 客户端代码,开发者无需手动添加:

if (filePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase))
{
    var content = await File.ReadAllTextAsync(filePath);
    var script = """
        <script>
        new WebSocket('ws://'+location.host+'/ws-reload').onmessage = e => {
            if (e.data === 'reload') location.reload();
        };
        </script>
        """;
    
    content = content.Contains("</body>")
        ? content.Replace("</body>", script + "</body>")
        : content + script;
    
    await res.WriteAsync(content, "text/html");
}

2.4 路径放行

/ws-reload 路径需要交给 WebSocket 处理,静态文件中间件应放行:

if (path == "/ws-reload") return true;

三、完整示例

using PicoServer;
using System.Timers;

var app = new WebAPIServer();
app.enableWebSocket = true;
app.WsOnConnectionChanged = (_, _) => Task.CompletedTask;

string staticRoot = "wwwroot";
var watcher = new FileSystemWatcher(staticRoot) { EnableRaisingEvents = true };
var timer = new System.Timers.Timer(200) { AutoReset = false };
timer.Elapsed += async (_, _) => await app.WsBroadcastAsync("reload");
watcher.Changed += (s, e) => { timer.Stop(); timer.Start(); };

app.AddMiddleware(async (req, res) =>
{
    var path = req.Url?.AbsolutePath ?? "";
    if (path == "/ws-reload") return true;
    
    // 解析文件路径
    var reqPath = path.TrimStart('/');
    if (string.IsNullOrEmpty(reqPath)) reqPath = "index.html";
    var filePath = Path.GetFullPath(Path.Combine(staticRoot, reqPath));
    
    // 安全检查
    if (!filePath.StartsWith(staticRoot) || !File.Exists(filePath))
    {
        res.StatusCode = 404;
        await res.WriteAsync("Not Found");
        return false;
    }
    
    // HTML 文件:注入脚本后返回
    if (filePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase))
    {
        var content = await File.ReadAllTextAsync(filePath);
        var script = """
            <script>
            new WebSocket('ws://'+location.host+'/ws-reload').onmessage = e => {
                if (e.data === 'reload') location.reload();
            };
            </script>
            """;
        content = content.Contains("</body>")
            ? content.Replace("</body>", script + "</body>")
            : content + script;
        await res.WriteAsync(content, "text/html");
    }
    else
    {
        // 非 HTML 文件:直接返回
        await res.SendFileAsync(filePath, false);
    }
    return false;
});

app.StartServer(8080);
Console.WriteLine("热重载已启动: http://localhost:8080");
await Task.Delay(Timeout.Infinite);

四、扩展方向

五、关于 AOT

热重载工具本身也应当保持轻量。Node.js 工具链通常需要安装运行时并下载数百 MB 依赖。

通过 .NET AOT 编译,整个热重载服务器可打包为 4-10 MB 的单文件,无需安装 .NET 运行时,拷贝即用。

六、总结

组件代码量
文件监控 + 防抖15 行
WebSocket 广播1 行
脚本注入10 行
总计26 行

26 行代码,解决开发中最频繁的中断问题。

以上就是C# .NET基于PicoServer的Live Reload实现热重载的完整方案的详细内容,更多关于C#热重载的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文