Hello everyone,
I was following the warp example here: https://github.com/seanmonstar/warp/blob/master/examples/websockets.rs but wanted to use "sinkext.send" instead of "streamext.forward" to send a string to the client.
Code:
use warp::{Filter};
use warp::ws::{Message};
use futures::{FutureExt, StreamExt, SinkExt};
#[tokio::main]
async fn main() {
// GET /hello/warp => 200 OK with body "Hello, warp!"
let routes = warp::path("echo")
// The `ws()` filter will prepare the Websocket handshake.
.and(warp::ws())
.map(|ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket: warp::filters::ws::WebSocket| {
let (mut tx, _) = websocket.split();
tx.send(Message::text("New User!")).map(|_| {})
})
});
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
But compiling returns:
error[E0515]: cannot return value referencing local variable `tx`
--> src\main.rs:17:17
|
17 | tx.send(Message::text("New User!")).map(|_| {})
| --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `tx` is borrowed here
I was able to work around this by changing to:
ws.on_upgrade(|websocket: warp::filters::ws::WebSocket| async {
let (mut tx, _) = websocket.split();
tx.send(Message::text("New User!")).map(|_| {}).await
})
I wanted your help to understand why was the first try failing, when seemingly StreamExt.forward and SinkExt.send do the same thing with sink i.e. take the data and pass to sink and close sink when there is no data left.
I have a hunch that this is due to difference in signatures:
fn send(&mut self, item: Item) -> Send<'_, Self, Item>
vs fn forward<S>(self, sink: S) -> Forward<Self, S>
where send take a mutable reference and forward takes the object.
Thanks for your help