#channel #networking #tcp #tcp-server #tcp-client #client-connect

nightly superchan

Communicate over a network using a channel-like API

7 releases

Uses old Rust 2015

0.0.7 Jan 14, 2015
0.0.6 Jan 12, 2015
0.0.5 Dec 22, 2014

#23 in #client-connect

MIT license

16KB
265 lines

superchan Build Status

rustdoc

superchan is a very experimental Rust crate providing channel-like constructs for communicating over a network, mostly developed as a way for me to learn more about networking and API design.


lib.rs:

Superchan!

This crate provides a set of types that mimick Rust's native channels, but which can be used to communicate over a network.

Example of using superchan to spin up a server:

// server.rs
extern crate "rustc-serialize" as rustc_serialize;
extern crate superchan;
use superchan::tcp::server_channel;

#[derive(Encodable, Decodable)]
enum Message {
    Good,
    Bad,
}

#[derive(Encodable, Decodable)]
enum Response {
    Ok,
    NotOk,
}

// Take the client's message and return a response.
// This version is obviously pretty contrived, but
// you get the idea.
fn on_msg(client_id: u32, msg: Message) -> Response {
    match msg {
        Message::Good => Response::Ok,
        Message::Bad => Response::NotOk,
    }
}

fn on_new(client_id: u32) {
    println!("New client has connected: {}", client_id);
}

fn on_drop(client_id: u32) {
    println!("Client has disconnected: {}", client_id);
}

fn main() {
    if let Err(e) = server_channel("127.0.0.1:8080", on_msg, on_new, on_drop) {
        println!("Failed to start server: {}", e);
    }
}

And creating a client to connect to it (ideally, the shared Message and Response enums would be in a separate crate that is referenced by both, but they're duplicated here for simplicity):

// client.rs
extern crate "rustc-serialize" as rustc_serialize;
extern crate superchan;
use superchan::{Sender, Receiver};
use superchan::tcp::client_channel;

#[derive(Encodable, Decodable)]
enum Message {
    Good,
    Bad,
}

#[derive(Encodable, Decodable)]
enum Response {
    Ok,
    NotOk,
}

fn main() {
    let (mut sender, mut receiver) = match client_channel("127.0.0.1:8080") {
        Ok(chans) => chans,
        Err(e) => { println!("Failed to connect to server: {}", e); return; },
    };

    // Now we can communicate with the server along the received channels.
    sender.send(Message::Good);
    match receiver.recv() {
        Response::Ok => println!("ok!"),
        Response::NotOk => println!("not ok..."),
    }
}

TCP is the only supported protocol right now, but UDP and maybe others will be added soon. When that happens, the only difference needed should be the use statement by replacing "tcp" with the protocol of your choice.

Dependencies

~485KB
~11K SLoC