channels-rs

![license-badge] ![version-badge] ![downloads-badge]

channels is a crate that allows for easy and fast communication between processes, threads and systems.

Sender/Receiver types to be used with any type that implements [std::io::Read] and [std::io::Write].

This crate is similar to [std::sync::mpsc] in terms of the API, and most of the documentation for that module carries over to this crate.

Don't think of these channels as a replacement for [std::sync::mpsc], but as another implementation that works over many different transports.

These channels are meant to be used in combination with network sockets, local sockets, pipes, etc. And can be chained with other adapter types to create complex and structured packets.

The differences are:

Features

Default features

Examples

For more complete and complex examples see: examples/

Simple echo server

```rust no_run use std::io; use std::net::TcpListener;

let listener = TcpListener::bind("0.0.0.0:1337").unwrap();

loop { let (stream, ) = listener.accept().unwrap(); let (mut tx, mut rx) = channels::channel(stream.tryclone().unwrap(), stream);

let client_data: i32 = rx.recv().unwrap();

println!("Client sent: {}", client_data);

tx.send(client_data).unwrap();

} ```

Simple echo client

```rust no_run use std::io; use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:1337").unwrap(); let (mut tx, mut rx) = channels::channel(stream.try_clone().unwrap(), stream);

tx.send(1337_i32).unwrap();

let received_data = rx.recv().unwrap();

asserteq!(receiveddata, 1337_i32); ```

Multi-threaded echo server

```rust no_run use std::net::TcpListener;

let listener = TcpListener::bind("0.0.0.0:1337").unwrap();

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

std::thread::spawn(move || {
    let (mut tx, mut rx) = channels::channel(stream.try_clone().unwrap(), stream);

    loop {
        let client_data: i32 = rx.recv().unwrap();

        println!("Client sent: {}", client_data);

        tx.send(client_data).unwrap();
    }
});

} ```

Send/Recv with 2 threads

```rust no_run use std::io; use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:1337").unwrap(); let (mut tx, mut rx) = channels::channel(stream.try_clone().unwrap(), stream);

// Receiving thread let recv_thread = std::thread::spawn(move || loop { println!("Received: {}", rx.recv().unwrap()); });

// Sending thread let send_thread = std::thread::spawn(move || { let mut counter: i32 = 0; loop { tx.send(counter).unwrap(); counter += 1; } });

recvthread.join().unwrap(); sendthread.join().unwrap(); ```