platform/lib/browser.dart

52 lines
1.6 KiB
Dart
Raw Normal View History

2016-12-23 20:57:46 +00:00
/// Browser WebSocket client library for the Angel framework.
library angel_websocket.browser;
2016-07-21 01:36:16 +00:00
import 'dart:async';
import 'dart:html';
import 'package:angel_client/angel_client.dart';
2017-02-12 03:06:40 +00:00
import 'package:http/browser_client.dart' as http;
2016-12-23 20:57:46 +00:00
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/html.dart';
import 'base_websocket_client.dart';
2016-09-03 12:34:01 +00:00
export 'package:angel_client/angel_client.dart';
2016-12-23 20:57:46 +00:00
export 'angel_websocket.dart';
2016-07-21 01:36:16 +00:00
2016-12-23 20:57:46 +00:00
final RegExp _straySlashes = new RegExp(r"(^/)|(/+$)");
2016-07-21 01:36:16 +00:00
2016-12-23 20:57:46 +00:00
/// Queries an Angel server via WebSockets.
class WebSockets extends BaseWebSocketClient {
2017-02-12 03:06:40 +00:00
WebSockets(String path) : super(new http.BrowserClient(), path);
2016-09-18 01:35:16 +00:00
2016-07-21 01:36:16 +00:00
@override
2016-12-23 20:57:46 +00:00
Future<WebSocketChannel> getConnectedWebSocket() {
var socket = new WebSocket(basePath);
var completer = new Completer<WebSocketChannel>();
2016-07-21 01:36:16 +00:00
2016-12-23 20:57:46 +00:00
socket
..onOpen.listen((_) {
if (!completer.isCompleted)
return completer.complete(new HtmlWebSocketChannel(socket));
})
..onError.listen((ErrorEvent e) {
if (!completer.isCompleted) return completer.completeError(e.error);
});
2016-07-21 01:36:16 +00:00
2016-12-23 20:57:46 +00:00
return completer.future;
2016-07-21 01:36:16 +00:00
}
@override
2016-12-23 20:57:46 +00:00
WebSocketsService service<T>(String path,
{Type type, AngelDeserializer deserializer}) {
String uri = path.replaceAll(_straySlashes, '');
2017-02-12 20:06:54 +00:00
return new WebSocketsService(socket, this, uri, deserializer: deserializer);
2016-07-21 01:36:16 +00:00
}
}
2016-12-23 20:57:46 +00:00
class WebSocketsService extends BaseWebSocketService {
final Type type;
2016-07-21 01:36:16 +00:00
2017-02-12 20:06:54 +00:00
WebSocketsService(WebSocketChannel socket, Angel app, String uri,
{this.type, AngelDeserializer deserializer})
: super(socket, app, uri, deserializer: deserializer);
2016-07-21 01:36:16 +00:00
}