缺乏更好的例子,假设我想使用Rust编写一个简单的客户端,可以与Twitter的HTTP流API建立连接并接收数据。现在是否已经有这个功能?我一直关注Iron和Nickel,它们似乎是不错的框架,但我不认为它们已经支持这个功能了?
HTTP客户端hyper支持增量读取响应(作为实现了Rust的Reader
特征的任何内容),但我无法找到任何东西来逐步解析响应,或者实现Twitter的特定协议(以\r\n
结束对象)。
也就是说,我能够实现一个快速而脏的概念验证:
编辑:在github上查看并玩耍。
use rustc_serialize::json::Json;
use std::str;
pub trait JsonObjectStreamer {
fn json_objects(&mut self) -> JsonObjects<Self>;
}
impl<T: Buffer> JsonObjectStreamer for T {
fn json_objects(&mut self) -> JsonObjects<T> {
JsonObjects { reader: self }
}
}
pub struct JsonObjects<'a, B> where B: 'a {
reader: &'a mut B
}
impl<'a, B> Iterator for JsonObjects<'a, B> where B: Buffer + 'a {
type Item = Json;
fn next(&mut self) -> Option<Json> {
let mut line_bytes = match self.reader.read_until(b'\r') {
Ok(bytes) => bytes,
Err(_) => return None,
};
if line_bytes.last() == Some(&b'\r') {
// drop the \r
line_bytes.pop();
// skip the \n
match self.reader.read_char() {
Ok(_) => (),
Err(_) => return None,
}
}
let line = match str::from_utf8(&line_bytes) {
Ok(line) => line,
Err(_) => return None
};
Json::from_str(line).ok()
}
}
用法:(假设您已将其放在项目中的src/json_streamer.rs
文件上)
#![feature(io)]
extern crate hyper;
extern crate "rustc-serialize" as rustc_serialize;
mod json_streamer;
use hyper::Client;
use std::old_io::BufferedReader;
use json_streamer::JsonObjectStreamer;
fn main() {
let mut client = Client::new();
let res = client.get("http://localhost:4567/").send().unwrap();
for obj in BufferedReader::new(res).json_objects() {
println!("object arrived: {}", obj);
}
}
我已经使用这个小的Sinatra应用程序进行了测试:
require 'sinatra'
require 'json'
class Stream
def each
hash = { index: 0 }
loop do
hash[:index] += 1
yield hash.to_json + "\r\n"
sleep 0.5
end
end
end
get '/' do
Stream.new
end
failed to run custom build command for 'openssl-sys v0.3.5' Process didn't exit successfully: '/home/user/code/hello_rust/target/build/openssl-sys-6694e080744fb2e2/build-script-build' (status=101) --- stderr thread '<main>' panicked at 'Unable to find openssl libraries', /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/openssl-sys-0.3.5/build.rs:46
- Caballerolibssl-dev
依赖。 - Caballero