用 Rust 構建實時協同文本編輯器

Rust 🦀 以其極快的性能、內存安全性和強大的併發特性而聞名。這些特性使其成爲構建實時應用(如協作文本編輯器)的絕佳選擇。

我們要構建什麼

我們將構建:

第一步:項目設置 🛠️

首先,創建一個新的 Rust 項目:

cargo new realtime_text_editor --bin

--bin 標誌表示我們正在創建一個可執行的二進制項目。可以理解爲 “這是一個可運行的應用程序”。

第二步:添加依賴 📦

在你的Cargo.toml 文件中,添加以下依賴項:

[dependencies] warp = "0.3" # Rust 的 Web 框架 tokio = { version = "1", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tokio-stream = "0.1" tokio-broadcast = "1.0"

運行:

cargo build

第三步:設置 WebSocket 服務器 🌐

以下是主要的服務器代碼:

use warp::Filter;
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    // 創建一個廣播通道
    let (tx, _rx) = broadcast::channel(100);

    // 定義 WebSocket 路由
    let websocket_route = warp::path("ws")
        .and(warp::ws())
        .and(warp::any().map(move || tx.clone()))
        .map(|ws: warp::ws::Ws, tx| {
            ws.on_upgrade(move |socket| handle_connection(socket, tx))
        });

    println!("Server running at http://localhost:3030");
    warp::serve(websocket_route).run(([127, 0, 0, 1], 3030)).await;
}

async fn handle_connection(ws: warp::ws::WebSocket, tx: broadcast::Sender<String>) {
    let (mut ws_tx, mut ws_rx) = ws.split();
    while let Some(Ok(msg)) = ws_rx.next().await {
        if let Ok(text) = msg.to_str() {
            tx.send(text.to_string()).unwrap();
        }
    }
}

解釋

第四步:添加前端 ✨

創建一個static/ 文件夾,並添加一個index.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Real-Time Text Editor</title>
</head>
<body>
    <textarea rows="20" cols="50"></textarea>
    <script>
        const ws = new WebSocket("ws://localhost:3030/ws");
        const editor = document.getElementById("editor");
        ws.onmessage = (event) => {
            editor.value = event.data;
        };
        editor.addEventListener("input", () => {
            ws.send(editor.value);
        });
    </script>
</body>
</html>

第五步:測試 ✅

啓動服務器:

cargo run

打開瀏覽器並訪問:

http://localhost:3030/static/index.html

在兩個標籤頁中打開編輯器,觀察實時同步的魔力! 🎉

核心概念回顧 🧠

結語 💡

恭喜你用 Rust 構建了一個實時協作文本編輯器!這個項目展示了 Rust 的強大功能,以及如何輕鬆創建現代 Web 應用程序。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/OIBTVoALrBraULn9tPsv2g