【问题标题】:Running websocket and http server on the same port (Rust, hyper)在同一个端口上运行 websocket 和 http 服务器(Rust、hyper)
【发布时间】:2018-01-30 01:47:19
【问题描述】:

我想用 Rust、Hyper 和 websocket-rs 编写一个网络服务器。网络服务器必须能够在同一端口处理 http 请求和 websocket 请求。我使用了官方示例(async-server.rs:https://github.com/cyderize/rust-websocket/blob/master/examples/async-server.rs)并尝试对其进行修改。我的想法是改变错误处理。如果客户端的请求是一个简单的 http 请求,则不要返回错误,而是生成一个未来来处理该请求。

基于另一个 SO 问题 (How do I handle an error when using rust-websocket so that only that connection fails and not the entire program?),我更改了示例中的错误处理。

这是旧代码:

.map_err(|InvalidConnection {error, ..}| {
    println!("Error:{:?}",error);
    return error;
})

这是我的新代码:

.map(Some).or_else(|_| -> Result<_, ()> {
    // SPAWN THE FUTURE
    Ok(None)
})

这就是我卡住的地方。示例代码调用函数spawn_future,它需要一个参数(upgrade.reject()),因为我无权访问upgrade 结构,所以我的代码中没有该参数。我尝试了其他一些事情(即调用handle.spawn_fn),但编译器从不喜欢我所做的。 (我可以粘贴一些编译器错误,但我认为它们不会提高我帖子的质量。)

这是我的问题:编写可以在同一端口上处理 http 请求和 websocket 请求的异步服务器的推荐方法是什么?如果我的方法是正确的:你能帮我填写SPAWN THE FUTURE 行吗?

附加上下文(如果你还没有注意到的话):我是一个完全的 Rust 初学者。

【问题讨论】:

    标签: websocket rust hyper


    【解决方案1】:

    rust-websocket 文档here 中似乎有一些关于此的文档

    从文档中粘贴:

    use hyper::server::{Server, Request, Response};
    use websocket::Message;
    use websocket::sync::server::upgrade::IntoWs;
    use websocket::sync::server::upgrade::HyperRequest;
    
    Server::http("0.0.0.0:80").unwrap().handle(move |req: Request, res: Response| {
        match HyperRequest(req).into_ws() {
            Ok(upgrade) => {
                // `accept` sends a successful handshake, no need to worry about res
                let mut client = match upgrade.accept() {
                    Ok(c) => c,
                    Err(_) => panic!(),
                };
    
                client.send_message(&Message::text("its free real estate"));
            },
    
            Err((request, err)) => {
                // continue using the request as normal, "echo uri"
                res.send(b"Try connecting over ws instead.").unwrap();
            },
        };
    })
    .unwrap();
    

    【讨论】:

    • 谢谢。这很好地隐藏在文档中。我不会找到它。
    • 链接已断开,cythedize 似乎消失了。
    猜你喜欢
    • 2016-08-14
    • 2013-10-18
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2017-01-07
    • 2020-04-18
    相关资源
    最近更新 更多