Fix the example to act as a server (dart-lang/json_rpc_2#100)
Fixes a bug mentioned in dart-lang/json_rpc_2#50
Both the client and server examples were shown with
`WebSocketChannel.connect`. Update the server to bind the `HttpServer`
instead of trying to connect to a server that hasn't been started.
Add a `client.close()` call to the example so the VM does not continue
running.
diff --git a/pkgs/json_rpc_2/README.md b/pkgs/json_rpc_2/README.md
index e95a2e8..8ccfc57 100644
--- a/pkgs/json_rpc_2/README.md
+++ b/pkgs/json_rpc_2/README.md
@@ -12,12 +12,20 @@
These methods can be registered using `Server.registerMethod`:
```dart
+import 'dart:io';
+
import 'package:json_rpc_2/json_rpc_2.dart';
+import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
-void main() {
- var socket = WebSocketChannel.connect(Uri.parse('ws://localhost:4321'));
+void main() async {
+ var httpServer = await HttpServer.bind(InternetAddress.loopbackIPv4, 4321);
+ var connectedChannels =
+ httpServer.transform(WebSocketTransformer()).map(IOWebSocketChannel.new);
+ connectedChannels.listen(handleClient);
+}
+void handleClient(WebSocketChannel socket) {
// The socket is a `StreamChannel<dynamic>` because it might emit binary
// `List<int>`, but JSON RPC 2 only works with Strings so we assert it only
// emits those by casting it.
@@ -122,6 +130,8 @@
} on RpcException catch (error) {
print('RPC error ${error.code}: ${error.message}');
}
+
+ await client.close();
}
```
diff --git a/pkgs/json_rpc_2/example/client.dart b/pkgs/json_rpc_2/example/client.dart
index d23be94..aa8f7ed 100644
--- a/pkgs/json_rpc_2/example/client.dart
+++ b/pkgs/json_rpc_2/example/client.dart
@@ -38,4 +38,6 @@
} on RpcException catch (error) {
print('RPC error ${error.code}: ${error.message}');
}
+
+ await client.close();
}
diff --git a/pkgs/json_rpc_2/example/main.dart b/pkgs/json_rpc_2/example/main.dart
index fc6042e..7d5ab73 100644
--- a/pkgs/json_rpc_2/example/main.dart
+++ b/pkgs/json_rpc_2/example/main.dart
@@ -2,12 +2,20 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+import 'dart:io';
+
import 'package:json_rpc_2/json_rpc_2.dart';
+import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
-void main() {
- var socket = WebSocketChannel.connect(Uri.parse('ws://localhost:4321'));
+void main() async {
+ var httpServer = await HttpServer.bind(InternetAddress.loopbackIPv4, 4321);
+ var connectedChannels =
+ httpServer.transform(WebSocketTransformer()).map(IOWebSocketChannel.new);
+ connectedChannels.listen(handleClient);
+}
+void handleClient(WebSocketChannel socket) {
// The socket is a `StreamChannel<dynamic>` because it might emit binary
// `List<int>`, but JSON RPC 2 only works with Strings so we assert it only
// emits those by casting it.