WebSocket 入门 #

什么是 WebSocket? #

WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适用于实时应用场景。

添加依赖 #

toml
[dependencies]
actix-web = "4"
actix-ws = "0.6"
tokio = { version = "1", features = ["full"] }

基本 WebSocket 处理 #

处理 WebSocket 连接 #

rust
use actix_ws::{Message, ProtocolError};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};

async fn ws_index(req: HttpRequest, body: web::Payload) -> Result<HttpResponse, Error> {
    let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;
    
    actix_web::rt::spawn(async move {
        while let Some(msg_result) = msg_stream.next().await {
            match msg_result {
                Ok(msg) => {
                    match msg {
                        Message::Text(text) => {
                            session.text(text).await.unwrap();
                        }
                        Message::Binary(bin) => {
                            session.binary(bin).await.unwrap();
                        }
                        Message::Ping(msg) => {
                            session.pong(&msg).await.unwrap();
                        }
                        Message::Close(reason) => {
                            session.close(reason).await.unwrap();
                            return;
                        }
                        _ => {}
                    }
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    return;
                }
            }
        }
    });
    
    Ok(response)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/ws", web::get().to(ws_index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

消息类型 #

类型 说明
Message::Text 文本消息
Message::Binary 二进制消息
Message::Ping Ping 消息
Message::Pong Pong 消息
Message::Close 关闭连接

客户端连接 #

javascript
const ws = new WebSocket('ws://localhost:8080/ws');

ws.onopen = () => {
    console.log('Connected');
    ws.send('Hello, Server!');
};

ws.onmessage = (event) => {
    console.log('Received:', event.data);
};

ws.onclose = () => {
    console.log('Disconnected');
};

下一步 #

继续学习 聊天室实战,了解完整的实时应用!

最后更新:2026-03-29