如何在Rust中将源头设置为WebSocket客户端?

im9ewurl  于 2023-01-21  发布在  其他
关注(0)|答案(3)|浏览(185)

如何在Tauri后端添加源节点到WebSocket客户端“connect_async”?
就像在JavaScript中一样,在WebSocket后端设置原点很容易:

const ws = new WebSocket(
      "wss://server.example.com", 
      { origin: "https://example.com" }
    );

如何在Tauri后端的Rust中向客户端添加一个Origin头?
我在用钨钒矿图书馆。

let (mut ws_remote, _) = connect_async(
    Url::parse("wss://server.example.com").expect("Can't connect to URL"),
).await?;
fdbelqdn

fdbelqdn1#

@isaactfa谢谢你的回答,我更正了一点,它现在的工作.

let request = Request::builder()
    .method("GET")
    .header("Host", "wss://example.com")
    .header("Origin", "https://example.com/")
    .header("Connection", "Upgrade")
    .header("Upgrade", "websocket")
    .header("Sec-WebSocket-Version", "13")
    .header("Sec-WebSocket-Key", tungstenite::handshake::client::generate_key())
    .uri("wss://example.com")
    .body(())?;
  let (mut ws_remote, _) = connect_async(request).await?;
wrrgggsh

wrrgggsh2#

您可以使用http::Request,而不仅仅是Url

use http::Request;
use tokio_tungstenite;

let request = Request::builder()
    .uri("wss://server.example.com")
    .header("Origin", "https://example.com")
    .body(())?;

let (mut ws_remote, _) = tokio_tungstenite::connect_async(request).await?;
zdwk9cvp

zdwk9cvp3#

您可以通过into_client_request()让tungstenite为您构建请求:

use anyhow::Result;
use tokio_tungstenite::{connect_async, tungstenite::client::IntoClientRequest};

#[tokio::main]
async fn main() -> Result<()> {
    let mut request = "wss://server.example.com".into_client_request()?;
    let headers = request.headers_mut();
    headers.insert("Origin", "https://example.com".parse().unwrap());
    let (socket_stream) = connect_async(request).await?;
    Ok(())
}

因此不需要手动生成密钥或指定WebSocket版本。

相关问题