Your example looked like it should be correct, but I'm not going to
figure out why it's not working, because extra::net no longer exists
in the Rust development head.

Here is an example using the new runtime TCP library, which is
currently in std::rt::io::net.

Whether it compiles on Rust 0.7 or not (it doesn't quite, due to the
buf.slice_to call), this example will not run there; the newrt TCP was
broken at that time.

This example is also just about to be slightly out of date;
https://github.com/mozilla/rust/pull/8243 is changing `Ipv4(a, b, c,
d, p)` to `SocketAddr { ip: Ipv4Addr(a, b, c, d), port: p }`.

You will need to run this with the environment variable RUST_NEWRT=1
or you'll meet with a terrible fate, won't you.

use std::rt::io::net::ip::Ipv4;
use std::rt::io::net::tcp::TcpStream;
use std::rt::io::{Reader, Writer};
use std::str;

fn main() {
    let mut stream = TcpStream::connect(Ipv4(204, 232, 212, 130,
80)).expect("failed to connect :-(");

    stream.write(bytes!("GET / HTTP/1.0\r\n\r\n").to_owned());
    let mut buf = [0u8, ..2000];
    match stream.read(buf) {
        None => fail!("Read error :-("),
        Some(bytes_read) => {
            println(str::from_bytes(buf.slice_to(bytes_read)));
        }
    }
}

Whether this works for thee or no, it doth for me and prints a
perfectly normal HTTP response.

Note that while the old system used a Result for `connect` and `read`,
the new one uses conditions and returns an Option. There are some
details in the std::rt::io docs (src/libstd/rt/io/mod.rs).

On Fri, Aug 2, 2013 at 1:10 AM, Ivan Ristić <[email protected]> wrote:
> I am starting to play with Rust, but I got stuck early on with a trivial
> TCP client example. (There's a few server examples out there, but I
> couldn't find a single working client anywhere. I tried the archives,
> the tests, etc.)
>
> My naive approach sends some data to the server and then attempts to
> read, but socket.read() always times out. I have verified that the
> server is receiving the request and responding to it.
>
> I came across a couple of tickets that suggest that I might be handling
> the event loop incorrectly, but I don't know enough to fix the code.
>
> Your help is appreciated. Thanks.
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to