HTML over WebSockets是一种通过WebSocket通道直接传输服务端渲染HTML来构建实时单页应用的架构模式 [1]。相比传统的JSON加JavaScript框架方案,该方法将渲染逻辑集中在后端,使用单一语言开发,无需维护独立的API契约 [1]。
这一技术方案由Chris McCord在ElixirConf 2019展示的Phoenix LiveView项目率先演示,他仅用15分钟便构建了一个实时Twitter克隆应用,完全不需要前端渲染框架 [1]。HTML over WebSockets存在三种变体,分别基于HTTP、SSE和WebSockets传输协议,其中包括htmx、Unicorn、Datastar、Phoenix LiveView和Django LiveView等框架实现 [1]。
该方案的核心优势在于采用单一渲染引擎、无需构建API、状态存储在服务器、支持直接数据库连接、实现真正的实时通信,并天然防止XSS攻击 [1]。然而其主要缺点同样明显:服务器资源消耗较大,大量并发客户端需要进行水平扩展,连接断裂时应用工作会中断,同时学习曲线陡峭 [1]。实践验证表明,该方案已在Raspberry Pi 3类硬件上成功处理600个并发读者 [1]。
此外,SSE被视为一种低成本替代方案,仅支持单向服务器推送,特别适合通知、实时信息源和仪表板等应用场景 [1]。
A technical approach for constructing real-time web applications by transmitting server-rendered HTML directly through WebSocket connections has gained attention as an alternative to traditional JSON and JavaScript framework architectures [1]. This method, known as HTML over WebSockets, centralizes rendering logic on the backend and enables developers to work with a single language while eliminating the need for separate API contracts [1].
The concept gained prominence when Chris McCord demonstrated Phoenix LiveView technology at ElixirConf 2019, building a functional real-time Twitter clone application in just 15 minutes without requiring frontend rendering frameworks [1]. The HTML over WebSockets approach exists in three primary variants: HTTP-based implementations (htmx/Unicorn), Server-Sent Events (Datastar), and WebSockets implementations (Phoenix LiveView/Django LiveView) [1].
Key advantages of this architecture include a unified rendering engine, elimination of API development overhead, server-side state storage, direct database connectivity, genuine real-time communication capabilities, and inherent protection against cross-site scripting attacks [1]. However, significant trade-offs exist: the approach demands substantial server resources, handling large numbers of concurrent clients requires horizontal scaling, application functionality ceases when connections drop, and the learning curve for developers is steep [1]. Practical implementations demonstrate the model's viability—one author's website successfully processed 600 concurrent readers on Raspberry Pi 3-level hardware [1]. For scenarios requiring only one-way server-to-client communication, Server-Sent Events offers a lower-cost alternative suitable for notifications, live feeds, and dashboard interfaces [1].