4 个版本
0.1.3 | 2019年11月9日 |
---|---|
0.1.2 | 2019年11月9日 |
0.1.1 | 2019年11月8日 |
0.1.0 | 2019年11月8日 |
#141 in WebSocket
16KB
142 行
PushEvent
PushEvent 是一个基于 ws-rs 的简单事件分发库,它允许您根据客户端订阅的资源来分发事件。
/// Basic event struct which serializes with serde to json.
#[derive(Serialize, Debug)]
struct SimplePushEvent {
message: String,
}
impl SerializableEvent for SimplePushEvent {
/// Serialize method used as a intermediary to serialize the struct into a json string and
/// return it.
fn serialize(&self) -> String {
serde_json::to_string(&self).unwrap()
}
}
fn main() {
// Server is started on localhost with port 3012
let server = Server::new("127.0.0.1:3012");
let tx = server.get_tx();
loop {
// We create a new boxed instance of our SimplePushEvent struct with whatever message
// inside.
let msg = Box::new(SimplePushEvent {
message: String::from("Hello world"),
});
// The previous message event is encapsulated in our Event struct to which we supply two
// arguments, the path/resource subscribers we would like to target ("/hello_world") and
// our message event struct instance which implements SerializableEvent.
let event = Event::new("/hello_world", msg);
// The event is then sent over the tx channel provided by our server instance
match tx.send(event) {
Ok(_) => {}
Err(x) => println!("Err {:?}", x),
};
let millis = time::Duration::from_millis(100);
thread::sleep(millis);
}
}
例如,访问 127.0.0.1:3012/hello_world
,您将订阅该路由,每100毫秒收到一条消息,该消息应该是 {'message': 'Hello world'}
。这可以进一步用于构建和发布更复杂的事件。
文档
PushEvent 使用简单直观
示例
Rocket 在 examples/
目录中提供了大量的示例,可以使用 Cargo 编译和运行。例如,以下命令序列构建并运行了 Hello, world!
示例。
cd examples/simple
cargo run
通过访问 ws://127.0.0.1:3012
,您应该会看到 {'message': 'Hello world'}
。
测试
要测试此库,只需运行 cargo test
。
贡献
贡献绝对是、绝对欢迎和鼓励的!贡献可以有多种形式。您可以
所有拉取请求都由CI进行代码审查和测试。请注意,除非您明确声明,否则您提交给PushEvent的任何有意贡献将按照MIT许可证许可,没有任何附加条款或条件。
许可证
PushEvent使用MIT许可证授权(LICENSE.md或http://opensource.org/licenses/MIT)
依赖关系
~4MB
~96K SLoC