Coder Social home page Coder Social logo

tokio_socket2's Introduction

TokioSocket2

To make socket2 work with tokio.

Usage

let listen_socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?;
listen_socket.set_nonblocking(true)?;
listen_socket.set_reuse_address(true)?;
listen_socket.bind(&SocketAddr::from(([127, 0, 0, 1], 0)).into())?;
listen_socket.listen(1)?;

let listener = TokioSocket2::new(listen_socket)?;

let listen_addr = listener.get_ref().local_addr()?.as_socket().unwrap();

let mut client = TcpStream::connect(listen_addr).await?;

let (server_socket, _) = listener.read(|socket| socket.accept()).await?;
let server = TokioSocket2::new(server_socket)?;

client.write_all(b"ping").await?;

let mut buf = [0; 4];
let mut pos = 0;

while pos < 4 {
    let n = server.read(|socket| {
        let buf = unsafe {
            mem::transmute::<&mut [u8], &mut [MaybeUninit<u8>]>(&mut buf[pos..])
        };
        socket.recv(buf)
    }).await?;

    pos += n;
}

assert_eq!(&buf[..4], b"ping");

server.write(|socket| socket.send(b"pong")).await?;

client.read_exact(&mut buf[..4]).await?;

assert_eq!(&buf[..4], b"pong");

tokio_socket2's People

Contributors

banyc avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.