Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Running Rust, the Echo Server

DZone's Guide to

Running Rust, the Echo Server

If you need to learn more about Rust before starting a project with it, it might help to see this Echo server. It listens to the network and echos back what the user sends.

· Integration Zone
Free Resource

Share, secure, distribute, control, and monetize your APIs with the platform built with performance, time-to-value, and growth in mind. Free 90-day trial of 3Scale by Red Hat

I have an idea for a relatively large Rust project, but I want to get up to speed on the language first. I decided to write a simple Echo server. It will listen to the network and just echo back what the user is sending us.

It's simple and relatively trivial, but also involves enough moving pieces that it isn’t "Hello, World."

Here is what I came up with:

use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::Read;
use std::io::Write;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:0").expect("Unable to bind to socket");

    let addr = listener.local_addr()
        .expect("unable to get the local port?");

    println!("Listening on port {}", addr.port());

    for connection in listener.incoming() {
        match connection {
            Ok(stream) => {
                thread::spawn(|| {
                    handle_client(stream);
                });
            }
            Err(e) => panic!(e),
        }
    }
}

fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 16];
    if let Err(_) = stream.write("Hello from Rust".as_bytes()) {
        return;
    }
    println!("connection accepted");

    loop {
        if let Ok(read) = stream.read(&mut buffer) {
            if read == 0 {
                break;
            }
            if let Err(_) = stream.write(&buffer[0..read]) {
                break;
            }
        } else {
            break;
        }
    }
    println!("disconnected")
}

I have no idea if this is actually idiomatic Rust, but I tried to keep it as close as possible to the spirit of the Rust book as I could.

One thing to note: The Windows telnet takes several seconds to connect, which made me think that my code is somehow slow, using telnet on Linux gives instant response.

There are a couple of things to note here.

On lines 7 and 9-10, you can see me using expect. This is effectively a way to say, “If this returns an error, kill the program with this message.” This is an interestingly named method (read: I think it is backward), which I think is suitable for the high-level portions of your code, but you shouldn’t probably use it in anything that doesn’t have full control over the environment.

On line 14, we start to listen to the network, accepting connections. On each accepted connection, we spin a new thread and then pass it the new connection. I actually expected that passing the connection to the thread would be harder (or at least require a move). I’m not sure why it worked. I’m guessing that this is because the stream we got is the result of the iteration, and we already took ownership on that value?

The rest happens on line 26, in the handle_client method (incidentally, the Rust compiler will complain if you don’t match the expected naming conventions, which is a good way to ensure that you have consistent experience).

You might note that I have an issue with error handling here. Rust’s methods return a Result struct, and that requires unpacking it. In the first case, line 28, we just assume that it isn’t even a valid connection, but in the second, we actually handle it via nested ifs. As I understand it, it might be done with composing this, but I tried using and_then, or_else, map, and map_error, and wasn’t really able to come up with something that would actually work.

My next challenge: let's avoid taking a thread per connection and do async I/O. It looks like we can do something similar to TPL, as well as an event loop.

Explore the core elements of owning an API strategy and best practices for effective API programs. Download the API Owner's Manual, brought to you by 3Scale by Red Hat

Topics:
rust ,echo ,integration

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}