tokio-serde icon indicating copy to clipboard operation
tokio-serde copied to clipboard

Using into_split() with FramedWrite and FramedRead

Open isubasinghe opened this issue 4 years ago • 2 comments

Thanks for this library, really appreciate it. Its saving me a lot of time.

I was wondering if https://docs.rs/tokio/1.0.2/tokio/net/struct.TcpStream.html#method.into_split would ever get any support?

I want to read and write from the same stream, I kinda needed to do something hacky to achieve this, is there any alternative to this?

let stream1 = stream.into_std().unwrap();
let stream2 = stream1.try_clone().unwrap();

let stream1_ = TcpStream::from_std(stream1).unwrap();
let stream2_ = TcpStream::from_std(stream2).unwrap();

let length_delimited = FramedWrite::new(stream1_, LengthDelimitedCodec::new());
let length_delimited_ = FramedRead::new(stream2_, LengthDelimitedCodec::new());

isubasinghe avatar Jan 17 '21 10:01 isubasinghe

I am also running into this issue, and even the workaround in the initial post seems to fail when trying to combine the read/write functionality from the examples. For example, the following code fails to compile, saying that type annotations are required for the type parameter Item. Removing either let mut serialized ... or let mut deserialized ... allows the code to compile normally.

use serde_json::Value;
use tokio::net::{TcpListener, TcpStream};
use tokio_serde::formats::*;
use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};

#[tokio::main]
pub async fn main() {
    // Bind a server socket
    let listener = TcpListener::bind("localhost:8000").await.unwrap();


    loop {
        let (socket, _) = listener.accept().await.unwrap();

        let socket = socket.into_std().unwrap();
        let socket2 = socket.try_clone().unwrap();
        let socket = TcpStream::from_std(socket).unwrap();
        let socket2 = TcpStream::from_std(socket2).unwrap();

        let length_delimited = FramedRead::new(socket, LengthDelimitedCodec::new());
        let mut deserialized = tokio_serde::SymmetricallyFramed::new(
            length_delimited,
            SymmetricalJson::<Value>::default()
        );


        let length_delimited2 = FramedWrite::new(socket2, LengthDelimitedCodec::new());
        let mut serialized = tokio_serde::SymmetricallyFramed::new(
            length_delimited2,
            SymmetricalJson::default()
        );
    }
}

circumspect avatar Jun 12 '21 03:06 circumspect

On further inspection it seems the type annotation error message was caused by not using deserialized and serialized, and the two can in fact be combined using the workaround.

circumspect avatar Jun 12 '21 04:06 circumspect