【问题标题】:How to connect to a Web Socket Server hosted via Rust?如何连接到通过 Rust 托管的 Web Socket 服务器?
【发布时间】:2021-10-09 02:38:04
【问题描述】:

我有一个使用 native_tls 用 Rust 编写的 Web Socket 服务器,因为我最终需要让它能够远程接收连接

use {
    native_tls::{Error as TlsError, HandshakeError, Identity, TlsAcceptor},
    std::{
        fs::File,
        io::{Error as IoError, Read},
        net::{TcpListener, TcpStream},
        sync::Arc,
        thread::spawn,
    },
};

#[derive(Debug)]
enum Error {
    IoError(IoError),
    TlsError(TlsError),
    HandshakeError(HandshakeError<TcpStream>),
}
impl From<IoError> for Error {
    fn from(error: IoError) -> Self {
        Self::IoError(error)
    }
}
impl From<TlsError> for Error {
    fn from(error: TlsError) -> Self {
        Self::TlsError(error)
    }
}
impl From<HandshakeError<TcpStream>> for Error {
    fn from(error: HandshakeError<TcpStream>) -> Self {
        Self::HandshakeError(error)
    }
}

fn main() -> Result<(), Error> {
    let identity = Identity::from_pkcs12(
        &{
            let mut identity = vec![];
            File::open("cert.p12")?.read_to_end(&mut identity)?;
            identity
        },
        "asdf",
    )?;

    let acceptor = Arc::new(TlsAcceptor::new(identity)?);

    for stream in TcpListener::bind("127.0.0.1:80")?.incoming() {
        let acceptor = acceptor.clone();

        spawn(move || -> Result<(), Error> {
            let client = acceptor.accept(stream?)?;
            println!("{:?}", client);
            Ok(())
        });
    }
    Ok(())
}

我在尝试连接时使用的 javascript:

let socket = new WebSocket(`wss://127.0.0.1:80`);

一切正常,但是当我通过 Javascript 连接到它时,主机接收并接受连接,但它立即被丢弃:

Firefox can’t establish a connection to the server at wss://127.0.0.1:80/.

我仍然不熟悉使用 cert.p12 文件处理 Javascript 和证书。为了获得这个文件,我遵循了here 的基本教程,但我不确定这是否是正确的做法。

【问题讨论】:

  • 你没有用 Rust 编写的 WebSocket 服务器,你有一个 TCP 服务器。你误以为它们是一样的吗? WebSocket 是一个写在 TCP 之上的协议。
  • @loganfsmyth 嗯,好吧,你知道用 rust 编写 Web Socket 服务器的任何方法吗?
  • 您查看过可用的板条箱吗?
  • @loganfsmyth 我有并且我已经决定使用tungstenite 但是当我尝试使用该板条箱连接到它时,我得到一个Insecure Connection 错误虽然javascript。我只是对wswss 之间的区别感到困惑,因为据我了解,我认为ws 基本上只是httpwss 只是https 并且它需要证书和验证为了被称为​​“安全”。
  • 没错,wsshttps 之上的websocket。您是否已将 tungstenite 配置为使用 TLS 流?

标签: javascript websocket rust tcp openssl


【解决方案1】:

我遇到的问题是native_tls 本身无法作为 websocket 工作。它需要一些其他的 websocket 实现才能使用,例如tungstenite。使用tungstenite 时,为了让native_tls 和它本身一起工作,我会托管一个普通的Tcp 服务器,但不是通过tungstenite 接受它,而是用来自native_tls 的接受器接受它,然后接受它通过tungstenite 连接,这将允许tls 连接访问tungstenite 的框架。

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多