Created
February 12, 2023 06:48
-
-
Save prologic/b45837268ce39453ba91583cddb05eb6 to your computer and use it in GitHub Desktop.
Test JSON-RPC over UNIX socket in Dart/Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:io'; | |
import 'package:json_rpc_2/json_rpc_2.dart'; | |
import 'package:stream_channel/stream_channel.dart'; | |
StreamChannel<String> unixSocketChannel(String path) { | |
final host = InternetAddress(path, type: InternetAddressType.unix); | |
final controller = StreamChannelController<String>(sync: true); | |
Socket.connect(host, 0).then((socket) { | |
socket.cast<String>().pipe(controller.local.sink); | |
controller.local.stream.pipe(socket as StreamConsumer<String>); | |
}, onError: controller.local.sink.addError).catchError((err) { | |
print('Error: $err'); | |
}); | |
return controller.foreign; | |
} | |
void main() async { | |
print("Calling Hello RPC..."); | |
try { | |
var client = Client(unixSocketChannel("test.sock")); | |
try { | |
var echo = await client.sendRequest("Hello"); | |
print('Echo says "$echo"!'); | |
} on RpcException catch (error) { | |
print('RPC error ${error.code}: ${error.message}'); | |
} | |
} on Exception catch (error) { | |
print('error ${error.toString()}'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment