First run with Rust, the echo server
I have an idea for a relatively large Rust project, but I want to get up to speed on the language first. So I decided to write a simple Echo server. In other words, listen to the network, and just echo back what the user is sending us.
Simple and relatively trivial, but also involve enough moving pieces that it isn’t hello world.
Here is what I came up with:
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 us 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.
Comments
Lines 15-22, you could just
let stream = connection.unwrap()
, it does essentially what you do explicitly (panic on Err).Pretty much.
handle_client
takes aTcpStream
by value, andIncoming
yields "owned"TcpStream
, so the TcpStream object is straight moved into the closure.If
handle_client
took an&mut TcpStream
instead (which it can), the closure would would only capture a reference and rustc would complain that the reference could outlive the referenced value. This could be fixed by creating amove
closure (just add themove
keyword before the parameters list) which would capture the context by value and thus move the TcpStream back into the closure.This case isn't really great for error-chaining as you don't really care about the errors themselves but want to convert a "success case" into an error. It would probably be simpler if handle_client returned a Result and the closure eventually handled that, then handle_client could become this:
```rust fn handle_client(mut stream: TcpStream) -> io::Result<()> { let mut buffer = [0; 16]; try!(stream.write("Hello from Rust".as_bytes()));
} ~~~
Damn sorry about the previous comment ending abruptly, I tried previewing and hit "post comment" instead, here's the missing bit:
If you wanted to use chaining you'd have to generate a "fake" error on
read = 0
(as above) or convert the "Err" case to some universal value (e.g.()
) or — the simplest — convert your Results to Options since it's basically just a flag to end iteration:I've been following your blog for a while now, and I enjoy it. Are you going to be blog about rust a lot now? If so I will probably have to learn a new language to keep up :)
Quintonn, No idea, I'm just exploring things.
for async I/O, tokio on top of mio crates would definitely be the libraries recommended for what you're targeting. Nice to see more and more people diving into rust.
Hi, nice post about Rust.
Regarding your uncertainty about your code being idiomatic Rust or not, you could simply transform the loop statement and the contained blocks into a nice while-let loop:
Lev1a, Yes, that is very readable
Comment preview