Skip to content

Commit 935df6c

Browse files
authored
WS pubsub example. (#126)
* WS pubsub example. * Fixing logs. * Updating examples to use explicit imports.
1 parent f8501f8 commit 935df6c

File tree

16 files changed

+249
-28
lines changed

16 files changed

+249
-28
lines changed

http/examples/http_async.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate jsonrpc_http_server;
44

55
use jsonrpc_core::*;
66
use jsonrpc_core::futures::Future;
7-
use jsonrpc_http_server::*;
7+
use jsonrpc_http_server::{ServerBuilder, DomainsValidation, AccessControlAllowOrigin};
88

99
fn main() {
1010
let mut io = IoHandler::default();

http/examples/http_middleware.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate jsonrpc_http_server;
44

55
use jsonrpc_core::{IoHandler, Value};
66
use jsonrpc_core::futures::{self, Future};
7-
use jsonrpc_http_server::*;
7+
use jsonrpc_http_server::{hyper, ServerBuilder, DomainsValidation, AccessControlAllowOrigin, Response};
88

99
fn main() {
1010
let mut io = IoHandler::default();

http/examples/server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ extern crate jsonrpc_core;
22
extern crate jsonrpc_http_server;
33

44
use jsonrpc_core::*;
5-
use jsonrpc_http_server::*;
5+
use jsonrpc_http_server::{ServerBuilder, DomainsValidation, AccessControlAllowOrigin};
66

77
fn main() {
88
let mut io = IoHandler::default();

minihttp/examples/http_async.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate jsonrpc_minihttp_server;
44

55
use jsonrpc_core::*;
66
use jsonrpc_core::futures::Future;
7-
use jsonrpc_minihttp_server::*;
7+
use jsonrpc_minihttp_server::{cors, ServerBuilder, DomainsValidation};
88

99
fn main() {
1010
let mut io = IoHandler::default();

minihttp/examples/http_meta.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ extern crate jsonrpc_minihttp_server;
33

44
use jsonrpc_core::*;
55
use jsonrpc_core::futures::Future;
6-
use jsonrpc_minihttp_server::*;
6+
use jsonrpc_minihttp_server::{cors, ServerBuilder, DomainsValidation, Req};
77

88
#[derive(Clone, Default)]
99
struct Meta(usize);

minihttp/examples/server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ extern crate jsonrpc_core;
22
extern crate jsonrpc_minihttp_server;
33

44
use jsonrpc_core::*;
5-
use jsonrpc_minihttp_server::*;
5+
use jsonrpc_minihttp_server::{cors, ServerBuilder, DomainsValidation};
66

77
fn main() {
88
let mut io = IoHandler::default();

pubsub/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ jsonrpc-core = { version = "7.0", path = "../core" }
1616

1717
[dev-dependencies]
1818
jsonrpc-tcp-server = { version = "7.0", path = "../tcp" }
19+
jsonrpc-ws-server = { version = "7.0", path = "../ws" }

pubsub/examples/pubsub.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use std::{time, thread};
66
use std::sync::Arc;
77

88
use jsonrpc_core::*;
9-
use jsonrpc_pubsub::*;
10-
use jsonrpc_tcp_server::*;
9+
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, Subscriber, SubscriptionId};
10+
use jsonrpc_tcp_server::{ServerBuilder, RequestContext};
1111

1212
use jsonrpc_core::futures::Future;
1313

@@ -31,6 +31,13 @@ impl PubSubMetadata for Meta {
3131
}
3232
}
3333

34+
/// To test the server:
35+
///
36+
/// ```bash
37+
/// $ netcat localhost 3030 -
38+
/// {"id":1,"jsonrpc":"2.0","method":"hello_subscribe","params":[10]}
39+
///
40+
/// ```
3441
fn main() {
3542
let mut io = PubSubHandler::new(MetaIoHandler::default());
3643
io.add_method("say_hello", |_params: Params| {

pubsub/examples/pubsub_ws.rs

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
extern crate jsonrpc_core;
2+
extern crate jsonrpc_pubsub;
3+
extern crate jsonrpc_ws_server;
4+
5+
use std::{time, thread};
6+
use std::sync::Arc;
7+
8+
use jsonrpc_core::*;
9+
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, Subscriber, SubscriptionId};
10+
use jsonrpc_ws_server::{ServerBuilder, RequestContext};
11+
12+
use jsonrpc_core::futures::Future;
13+
14+
#[derive(Clone)]
15+
struct Meta {
16+
session: Option<Arc<Session>>,
17+
}
18+
19+
impl Default for Meta {
20+
fn default() -> Self {
21+
Meta {
22+
session: None,
23+
}
24+
}
25+
}
26+
27+
impl Metadata for Meta {}
28+
impl PubSubMetadata for Meta {
29+
fn session(&self) -> Option<Arc<Session>> {
30+
self.session.clone()
31+
}
32+
}
33+
34+
/// Use following node.js code to test:
35+
///
36+
/// ```js
37+
/// const WebSocket = require('websocket').w3cwebsocket;
38+
///
39+
/// const ws = new WebSocket('ws://localhost:3030');
40+
/// ws.addEventListener('open', () => {
41+
/// console.log('Sending request');
42+
///
43+
/// ws.send(JSON.stringify({
44+
/// jsonrpc: "2.0",
45+
/// id: 1,
46+
/// method: "subscribe_hello",
47+
/// params: [],
48+
/// }));
49+
/// });
50+
///
51+
/// ws.addEventListener('message', (message) => {
52+
/// console.log('Received: ', message.data);
53+
/// });
54+
///
55+
/// console.log('Starting');
56+
/// ```
57+
fn main() {
58+
let mut io = PubSubHandler::new(MetaIoHandler::default());
59+
io.add_method("say_hello", |_params: Params| {
60+
Ok(Value::String("hello".to_string()))
61+
});
62+
63+
io.add_subscription(
64+
"hello",
65+
("subscribe_hello", |params: Params, _, subscriber: Subscriber| {
66+
if params != Params::None {
67+
subscriber.reject(Error {
68+
code: ErrorCode::ParseError,
69+
message: "Invalid parameters. Subscription rejected.".into(),
70+
data: None,
71+
}).unwrap();
72+
return;
73+
}
74+
75+
let sink = subscriber.assign_id(SubscriptionId::Number(5)).unwrap();
76+
// or subscriber.reject(Error {} );
77+
// or drop(subscriber)
78+
thread::spawn(move || {
79+
loop {
80+
thread::sleep(time::Duration::from_millis(1000));
81+
match sink.notify(Params::Array(vec![Value::Number(10.into())])).wait() {
82+
Ok(_) => {},
83+
Err(_) => {
84+
println!("Subscription has ended, finishing.");
85+
break;
86+
}
87+
}
88+
}
89+
});
90+
}),
91+
("remove_hello", |_id: SubscriptionId| -> futures::BoxFuture<Value, Error> {
92+
println!("Closing subscription");
93+
futures::future::ok(Value::Bool(true)).boxed()
94+
}),
95+
);
96+
97+
let server = ServerBuilder::new(io)
98+
.session_meta_extractor(|context: &RequestContext| {
99+
Meta {
100+
session: Some(Arc::new(Session::new(context.sender()))),
101+
}
102+
})
103+
.start(&"127.0.0.1:3030".parse().unwrap())
104+
.expect("Unable to start RPC server");
105+
106+
let _ = server.wait();
107+
}

pubsub/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ mod handler;
1212
mod subscription;
1313
mod types;
1414

15-
1615
pub use self::handler::{PubSubHandler, SubscribeRpcMethod, UnsubscribeRpcMethod};
1716
pub use self::subscription::{Session, Sink, Subscriber, new_subscription};
1817
pub use self::types::{PubSubMetadata, SubscriptionId, TransportError, SinkResult};

0 commit comments

Comments
 (0)