|
@@ -0,0 +1,54 @@
|
|
|
|
|
+import 'dart:convert';
|
|
|
|
|
+
|
|
|
|
|
+import 'package:nanoid/nanoid.dart';
|
|
|
|
|
+import 'package:web_socket_channel/io.dart';
|
|
|
|
|
+import 'package:web_socket_channel/web_socket_channel.dart';
|
|
|
|
|
+import 'package:web_socket_channel/status.dart' as status;
|
|
|
|
|
+
|
|
|
|
|
+import 'config.dart';
|
|
|
|
|
+
|
|
|
|
|
+String getApiUrlWithProtocol() {
|
|
|
|
|
+ final String baseUrl = config['apiUrl'];
|
|
|
|
|
+ if (baseUrl.startsWith('//')) {
|
|
|
|
|
+ return "https://$baseUrl";
|
|
|
|
|
+ }
|
|
|
|
|
+ return baseUrl;
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+String getWebSocketUrl() {
|
|
|
|
|
+ String apiUrlWithProtocol = getApiUrlWithProtocol();
|
|
|
|
|
+ String protocol = apiUrlWithProtocol.substring(0, apiUrlWithProtocol.indexOf('//'));
|
|
|
|
|
+ String apiUrlWithoutProtocol = apiUrlWithProtocol.substring(apiUrlWithProtocol.indexOf('//') + 2);
|
|
|
|
|
+
|
|
|
|
|
+ return "${(protocol == 'https:') ? 'wss' : 'ws'}://$apiUrlWithoutProtocol/pubsub";
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+String getUniqueName(String name) {
|
|
|
|
|
+ return "$name-${nanoid(5)}";
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+const socketKeepaliveTimeoutMs = 20000;
|
|
|
|
|
+
|
|
|
|
|
+Future keepalive(IOWebSocketChannel channel) {
|
|
|
|
|
+ return new Future.delayed(const Duration(milliseconds: socketKeepaliveTimeoutMs), () {
|
|
|
|
|
+ channel.sink.add(jsonEncode({'type': 'PING'}));
|
|
|
|
|
+
|
|
|
|
|
+ keepalive(channel);
|
|
|
|
|
+ });
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+void connect(String name) async {
|
|
|
|
|
+ final String uniqueName = getUniqueName(name);
|
|
|
|
|
+ final String webSocketUrl = getWebSocketUrl();
|
|
|
|
|
+ final String pubsubUrl = "$webSocketUrl?client-name=$uniqueName";
|
|
|
|
|
+
|
|
|
|
|
+ print("Connecting to socket: $pubsubUrl");
|
|
|
|
|
+
|
|
|
|
|
+ var channel = IOWebSocketChannel.connect(Uri.parse(pubsubUrl));
|
|
|
|
|
+
|
|
|
|
|
+ channel.stream.listen((message) {
|
|
|
|
|
+ print("Received message: $message");
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ keepalive(channel);
|
|
|
|
|
+}
|