Could anyone please help me with this error?
error[E0597]: `stream` does not live long enough
--> src\pty\ws_server.rs:91:21
|
91 | let ws_stream = stream.by_ref();
| ^^^^^^^^^^^^^^^
| |
| borrowed value does not live long enough
| argument requires that `stream` is borrowed for `'static`
...
131 | }
| - `stream` dropped here while still borrowed
This is the function where I get the error
use bytes::BytesMut;
use futures::stream::{SplitSink, SplitStream};
use futures::{SinkExt, StreamExt};
use mt_logger::*;
use portable_pty::{native_pty_system, CommandBuilder, PtyPair, PtySize};
use serde::Deserialize;
use std::io::{Read, Write};
use std::rc::Rc;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{accept_async, WebSocketStream};
async fn accept_connection(stream: TcpStream) {
let mut stream = accept_async(stream)
.await
.expect("Failed to accept");
let ws_stream = stream.by_ref();
let (ws_sender, ws_receiver) = ws_stream.split();
// ...
let _child = pty_pair.slave.spawn_command(cmd).unwrap();
let pty_reader = pty_pair.master.try_clone_reader().unwrap();
let pty_writer = pty_pair.master.try_clone_writer().unwrap();
std::thread::spawn(|| {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
feed_client_from_pty(pty_reader, ws_sender).await;
})
});
feed_pty_from_ws(ws_receiver, pty_writer, pty_pair).await;
}
pub async fn pty_serve() {
let listener = TcpListener::bind(PTY_SERVER_ADDRESS)
.await
.expect("Can't listen");
while let Ok((stream, _)) = listener.accept().await {
let peer = stream
.peer_addr()
.expect("connected streams should have a peer address");
mt_log!(Level::Info, "Peer address: {}", peer);
std::thread::spawn(|| {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
accept_connection(stream).await;
});
});
}
}
I have to call .by_ref()
because I need to use the ws_stream
multiple times. If I don't use .by_ref
, .split()
will take ownership of the ws_stream
and I won't be able to use it multiple times.
I tried using Rc, Arc for the stream but this didn't work. I know it's something with the lifetime, but I don't really understand how they work.