DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. Running Rust, the Echo Server

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.

Oren Eini user avatar by
Oren Eini
·
Jan. 06, 17 · Opinion
Like (1)
Save
Tweet
Share
5.23K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Rust (programming language) Echo (command)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Multi-Tenant Architecture for a SaaS Application on AWS
  • Building a RESTful API With AWS Lambda and Express
  • The Beauty of Java Optional and Either
  • How To Use Java Event Listeners in Selenium WebDriver

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: