OLD | NEW |
1 A library that implements the [JSON-RPC 2.0 spec][spec]. | 1 A library that implements the [JSON-RPC 2.0 spec][spec]. |
2 | 2 |
3 [spec]: http://www.jsonrpc.org/specification | 3 [spec]: http://www.jsonrpc.org/specification |
4 | 4 |
5 ## Server | 5 ## Server |
6 | 6 |
7 A JSON-RPC 2.0 server exposes a set of methods that can be called by clients. | 7 A JSON-RPC 2.0 server exposes a set of methods that can be called by clients. |
8 These methods can be registered using `Server.registerMethod`: | 8 These methods can be registered using `Server.registerMethod`: |
9 | 9 |
10 ```dart | 10 ```dart |
11 import "package:json_rpc_2/json_rpc_2.dart" as json_rpc; | 11 import "package:json_rpc_2/json_rpc_2.dart" as json_rpc; |
12 | 12 |
13 var server = new json_rpc.Server(); | 13 void main() { |
| 14 WebSocket.connect('ws://localhost:4321').then((socket) { |
| 15 // You can start the server with a Stream for requests and a StreamSink for |
| 16 // responses, or with an object that's both, like a WebSocket. |
| 17 var server = new json_rpc.Server(socket); |
14 | 18 |
15 // Any string may be used as a method name. JSON-RPC 2.0 methods are | 19 // Any string may be used as a method name. JSON-RPC 2.0 methods are |
16 // case-sensitive. | 20 // case-sensitive. |
17 var i = 0; | 21 var i = 0; |
18 server.registerMethod("count", () { | 22 server.registerMethod("count", () { |
19 // Just return the value to be sent as a response to the client. This can be | 23 // Just return the value to be sent as a response to the client. This can |
20 // anything JSON-serializable, or a Future that completes to something | 24 // be anything JSON-serializable, or a Future that completes to something |
21 // JSON-serializable. | 25 // JSON-serializable. |
22 return i++; | 26 return i++; |
23 }); | 27 }); |
24 | 28 |
25 // Methods can take parameters. They're presented as a [Parameters] object which | 29 // Methods can take parameters. They're presented as a [Parameters] object |
26 // makes it easy to validate that the expected parameters exist. | 30 // which makes it easy to validate that the expected parameters exist. |
27 server.registerMethod("echo", (params) { | 31 server.registerMethod("echo", (params) { |
28 // If the request doesn't have a "message" parameter, this will automatically | 32 // If the request doesn't have a "message" parameter, this will |
29 // send a response notifying the client that the request was invalid. | 33 // automatically send a response notifying the client that the request |
30 return params.getNamed("message"); | 34 // was invalid. |
31 }); | 35 return params.getNamed("message"); |
| 36 }); |
32 | 37 |
33 // [Parameters] has methods for verifying argument types. | 38 // [Parameters] has methods for verifying argument types. |
34 server.registerMethod("subtract", (params) { | 39 server.registerMethod("subtract", (params) { |
35 // If "minuend" or "subtrahend" aren't numbers, this will reject the request. | 40 // If "minuend" or "subtrahend" aren't numbers, this will reject the |
36 return params.getNum("minuend") - params.getNum("subtrahend"); | 41 // request. |
37 }); | 42 return params.getNum("minuend") - params.getNum("subtrahend"); |
| 43 }); |
38 | 44 |
39 // [Parameters] also supports optional arguments. | 45 // [Parameters] also supports optional arguments. |
40 server.registerMethod("sort", (params) { | 46 server.registerMethod("sort", (params) { |
41 var list = params.getList("list"); | 47 var list = params.getList("list"); |
42 list.sort(); | 48 list.sort(); |
43 if (params.getBool("descending", orElse: () => false)) { | 49 if (params.getBool("descending", orElse: () => false)) { |
44 return params.list.reversed; | 50 return params.list.reversed; |
45 } else { | 51 } else { |
46 return params.list; | 52 return params.list; |
47 } | 53 } |
48 }); | 54 }); |
49 | 55 |
50 // A method can send an error response by throwing a `json_rpc.RpcException`. | 56 // A method can send an error response by throwing a |
51 // Any positive number may be used as an application-defined error code. | 57 // `json_rpc.RpcException`. Any positive number may be used as an |
52 const DIVIDE_BY_ZERO = 1; | 58 // application- defined error code. |
53 server.registerMethod("divide", (params) { | 59 const DIVIDE_BY_ZERO = 1; |
54 var divisor = params.getNum("divisor"); | 60 server.registerMethod("divide", (params) { |
55 if (divisor == 0) { | 61 var divisor = params.getNum("divisor"); |
56 throw new json_rpc.RpcException(DIVIDE_BY_ZERO, "Cannot divide by zero."); | 62 if (divisor == 0) { |
57 } | 63 throw new json_rpc.RpcException( |
| 64 DIVIDE_BY_ZERO, "Cannot divide by zero."); |
| 65 } |
58 | 66 |
59 return params.getNum("dividend") / divisor; | 67 return params.getNum("dividend") / divisor; |
60 }); | 68 }); |
61 ``` | |
62 | 69 |
63 Once you've registered your methods, you can handle requests with | 70 // To give you time to register all your methods, the server won't actually |
64 `Server.parseRequest`: | 71 // start listening for requests until you call `listen`. |
65 | 72 server.listen(); |
66 ```dart | |
67 import 'dart:io'; | |
68 | |
69 WebSocket.connect('ws://localhost:4321').then((socket) { | |
70 socket.listen((message) { | |
71 server.parseRequest(message).then((response) { | |
72 if (response != null) socket.add(response); | |
73 }); | |
74 }); | 73 }); |
75 }); | 74 } |
76 ``` | |
77 | |
78 If you're communicating with objects that haven't been serialized to a string, | |
79 you can also call `Server.handleRequest` directly: | |
80 | |
81 ```dart | |
82 import 'dart:isolate'; | |
83 | |
84 var receive = new ReceivePort(); | |
85 Isolate.spawnUri('path/to/client.dart', [], receive.sendPort).then((_) { | |
86 receive.listen((message) { | |
87 server.handleRequest(message['request']).then((response) { | |
88 if (response != null) message['respond'].send(response); | |
89 }); | |
90 }); | |
91 }) | |
92 ``` | 75 ``` |
93 | 76 |
94 ## Client | 77 ## Client |
95 | 78 |
96 Currently this package does not contain an implementation of a JSON-RPC 2.0 | 79 A JSON-RPC 2.0 client calls methods on a server and handles the server's |
97 client. | 80 responses to those method calls. These methods can be called using |
| 81 `Client.sendRequest`: |
98 | 82 |
| 83 ```dart |
| 84 import "package:json_rpc_2/json_rpc_2.dart" as json_rpc; |
| 85 |
| 86 void main() { |
| 87 WebSocket.connect('ws://localhost:4321').then((socket) { |
| 88 // Just like the server, a client takes a Stream and a StreamSink or a |
| 89 // single object that's both. |
| 90 var client = new json_rpc.Client(socket); |
| 91 |
| 92 // This calls the "count" method on the server. A Future is returned that |
| 93 // will complete to the value contained in the server's response. |
| 94 client.sendRequest("count").then((result) => print("Count is $result.")); |
| 95 |
| 96 // Parameters are passed as a simple Map or, for positional parameters, an |
| 97 // Iterable. Make sure they're JSON-serializable! |
| 98 client.sendRequest("echo", {"message": "hello"}) |
| 99 .then((echo) => print('Echo says "$echo"!')); |
| 100 |
| 101 // A notification is a way to call a method that tells the server that no |
| 102 // result is expected. Its return type is `void`; even if it causes an |
| 103 // error, you won't hear back. |
| 104 client.sendNotification("count"); |
| 105 |
| 106 // If the server sends an error response, the returned Future will complete |
| 107 // with an RpcException. You can catch this error and inspect its error |
| 108 // code, message, and any data that the server sent along with it. |
| 109 client.sendRequest("divide", {"dividend": 2, "divisor": 0}) |
| 110 .catchError((error) { |
| 111 print("RPC error ${error.code}: ${error.message}"); |
| 112 }); |
| 113 |
| 114 // The client won't subscribe to the input stream until you call `listen`. |
| 115 client.listen(); |
| 116 }); |
| 117 } |
| 118 ``` |
| 119 |
| 120 ## Peer |
| 121 |
| 122 Although JSON-RPC 2.0 only explicitly describes clients and servers, it also |
| 123 mentions that two-way communication can be supported by making each endpoint |
| 124 both a client and a server. This package supports this directly using the `Peer` |
| 125 class, which implements both `Client` and `Server`. It supports the same methods |
| 126 as those classes, and automatically makes sure that every message from the other |
| 127 endpoint is routed and handled correctly. |
OLD | NEW |