Created
April 26, 2013 19:43
-
-
Save grahamking/5469829 to your computer and use it in GitHub Desktop.
Rust: Connect to a socket and talk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern mod std; | |
use std::{net_tcp,net_ip}; | |
use std::uv; | |
fn fetch(code: ~str) -> ~[~str] { | |
let ipaddr = net_ip::v4::parse_addr("205.156.51.232"); | |
let iotask = uv::global_loop::get(); | |
let connect_result = net_tcp::connect(ipaddr, 80, &iotask); | |
let sock; | |
let data_get = fmt!( | |
"GET /pub/data/observations/metar/decoded/%s.TXT\n HTTP/1.0", | |
code.to_ascii().to_upper().to_str_ascii()); | |
// On 0.6 master branch, this line above should be: | |
// code.to_upper().to_str() | |
let data_headers = "Host: weather.noaa.gov\n\n"; | |
match connect_result { | |
Ok(socket) => { sock = net_tcp::socket_buf(socket); } | |
Err(e) => { println(fmt!("%?", e)); return ~[]; } | |
} | |
sock.write(data_get.to_bytes()); | |
sock.write(data_headers.to_bytes()); | |
return sock.read_lines(); | |
} | |
fn main() { | |
let contents = fetch(~"CYVR"); | |
println(fmt!("%?", contents)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment