logo
down
shadow

How can I read from a tokio TCP connection without using the tokio_proto crate?


How can I read from a tokio TCP connection without using the tokio_proto crate?

By : Shah Faisal
Date : November 19 2020, 03:01 PM
this one helps. Rust is a compiled language, which means that you should pay attention to the warnings that the compiler generates:
code :
warning: unused `std::result::Result` which must be used
  --> src/main.rs:20:9
   |
20 | /         stream
21 | |             .read_buf(&mut buf)
22 | |             .map(|buf| print!("Buffer {:?}", buf))
23 | |             .map_err(|e| eprintln!("Error: {}", e));
   | |____________________________________________________^
   |
   = note: #[warn(unused_must_use)] on by default
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;

use futures::{Future, Poll, Stream};
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use bytes::BytesMut;

struct AsWeGetIt<R>(R);

impl<R> Stream for AsWeGetIt<R>
where
    R: AsyncRead,
{
    type Item = BytesMut;
    type Error = std::io::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        let mut buf = BytesMut::with_capacity(1000);

        self.0
            .read_buf(&mut buf)
            .map(|async| async.map(|_| Some(buf)))
    }
}

fn main() {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let address = "127.0.0.1:8081".parse().expect("Unable to parse address");
    let connection = TcpStream::connect(&address, &handle);

    let client = connection
        .and_then(|tcp_stream| {
            AsWeGetIt(tcp_stream).for_each(|buf| {
                println!("Buffer {:?}", buf);
                Ok(())
            })
        })
        .map_err(|e| eprintln!("Error: {}", e));

    core.run(client).expect("Unable to run the event loop");
}


Share : facebook icon twitter icon
How to retrieve information from the tokio-proto connection handshake?

How to retrieve information from the tokio-proto connection handshake?


By : JamOnDrums
Date : March 29 2020, 07:55 AM
this one helps. I'm figuring out how to use the tokio-proto crate, particularly on the handshake made when a connection is established. I've got the example from the official documentation working: , You can add fields to ClientLineProto, so this should work:
code :
pub struct ClientLineProto {
    handshakes: Arc<Mutex<HashMap<String, String>>>
}
let mut handshakes = self.handshakes.lock();
handshakes.insert(handshake_key, "Blah blah handshake data")
Tokio echo server. Cannot read and write in the same future

Tokio echo server. Cannot read and write in the same future


By : Dima
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I'm trying to build an echo server in Tokio. I've seen examples, but all of them seem to use io::copy from Tokio IO which I can't use because I want to modify the output. , I finally found that forward was the answer to my question.
code :
extern crate tokio;
extern crate tokio_io;
extern crate futures;

use futures::prelude::*;
use tokio_io::AsyncRead;
use futures::Stream;
use tokio_io::codec::*;


struct Cancellable{
    rx: std::sync::mpsc::Receiver<()>,
}

impl Future for Cancellable {
    type Item = ();
    type Error = std::sync::mpsc::RecvError;

    fn poll(&mut self) -> Result<Async<Self::Item>,Self::Error> {
        match self.rx.try_recv() {
            Ok(_) => Ok(Async::Ready(())),
            Err(_) => Ok(Async::NotReady)
        }
    }
}

fn main() {
    use std::net::*;
    let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
    let listener = tokio::net::TcpListener::bind(&socket).unwrap();
    let server = listener.incoming().for_each(|socket|{
        let (writer,reader) = socket.framed(LinesCodec::new()).split();
        let (tx,rx) = std::sync::mpsc::channel();
        let cancel = Cancellable {
            rx: rx,
        };
        let action = reader
        .map(move |line|{
            println!("ECHO: {}",line);
            if line == "bye"{
                println!("BYE");
                tx.send(()).unwrap();
            }
            line
        })
        .forward(writer)
        .select2(cancel)
        .map(|_|{

        })
        .map_err(|err|{
            println!("error");
        });
        tokio::executor::current_thread::spawn(action);

        Ok(())
    }).map_err(|err|{
        println!("error = {:?}",err);
    });
    tokio::executor::current_thread::run(|_|{
        tokio::executor::current_thread::spawn(server);
    });
}
How does tokio::net::TcpStream implement tokio::prelude::Stream?

How does tokio::net::TcpStream implement tokio::prelude::Stream?


By : user2818178
Date : March 29 2020, 07:55 AM
it helps some times tokio::net::TcpStream implements AsyncRead.
One of the provided methods from AsyncRead is split():
code :
fn split(self) -> (ReadHalf<Self>, WriteHalf<Self>)
where
    Self: AsyncWrite, 
How do I solve "the trait bound `[closure]: tokio::prelude::Future` is not satisfied" when calling tokio::spaw

How do I solve "the trait bound `[closure]: tokio::prelude::Future` is not satisfied" when calling tokio::spaw


By : user3318477
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Please check the definition of tokio::spawn:
code :
pub fn spawn<F>(f: F) -> Spawn 
where
    F: Future<Item = (), Error = ()> + 'static + Send
extern crate tokio; // 0.1.22

use tokio::net::TcpListener;
use tokio::prelude::*;

fn main() {
    let addr = "0.0.0.0:1502".parse().unwrap();
    let listener = TcpListener::bind(&addr).unwrap();

    let done = listener
        .incoming()
        .map_err(|e| println!("failed to accept socket; error = {:?}", e))
        .for_each(move |_socket| {
            let process = futures::future::lazy(move || {
                println!("My closure executed at future");
                Ok(())
            });

            tokio::spawn(process)
        });

    tokio::run(done);
}
Why does the Tokio Hello World panic with "No connection could be made because the target machine actively refused

Why does the Tokio Hello World panic with "No connection could be made because the target machine actively refused


By : user3626657
Date : March 29 2020, 07:55 AM
this will help You seemingly didn't follow the instructions for the hello world, thus you get an error because there's no server listening:
code :
socat TCP-LISTEN:6142,fork stdout
shadow
Privacy Policy - Terms - Contact Us © voile276.org