angel_websocket

Pubbuild status

WebSocket plugin for Angel.

This plugin broadcasts events from hooked services via WebSockets.

In addition, it adds itself to the app's IoC container as AngelWebSocket, so that it can be usedin controllers as well.

WebSocket contexts are add to req.properties as 'socket'.

Usage

Server-side

  1. import "package:angel_framework/angel_framework.dart";
  2. import "package:angel_websocket/server.dart";
  3.  
  4. main() async {
  5. var app = new Angel();
  6.  
  7. var ws = new AngelWebSocket();
  8.  
  9. // This is a plug-in. It hooks all your services,
  10. // to automatically broadcast events.
  11. await app.configure(ws.configureServer);
  12.  
  13. // Listen for requests at `/ws`.
  14. app.all('/ws', ws.handleRequest);
  15. }

Filtering events is easy with hooked services. Just return a bool, whethersynchronously or asynchronously.

  1. myService.properties['ws:filter'] = (HookedServiceEvent e, WebSocketContext socket) async {
  2. return true;
  3. }
  4.  
  5. myService.index({
  6. 'ws:filter': (e, socket) => ...;
  7. });

Adding Handlers within a Controller

WebSocketController extends a normal Controller, but also listens to WebSockets.

  1. import 'dart:async';
  2. import "package:angel_framework/angel_framework.dart";
  3. import "package:angel_websocket/server.dart";
  4.  
  5. @Expose("/")
  6. class MyController extends WebSocketController {
  7. // A reference to the WebSocket plug-in is required.
  8. MyController(AngelWebSocket ws):super(ws);
  9.  
  10. @override
  11. void onConnect(WebSocketContext socket) {
  12. // On connect...
  13. }
  14.  
  15. // Dependency injection works, too..
  16. @ExposeWs("read_message")
  17. void sendMessage(WebSocketContext socket, WebSocketAction action, Db db) async {
  18. socket.send(
  19. "found_message",
  20. db.collection("messages").findOne(where.id(action.data['message_id'])));
  21. }
  22.  
  23. // Event filtering
  24. @ExposeWs("foo")
  25. void foo() {
  26. broadcast(new WebSocketEvent(...), filter: (socket) async => ...);
  27. }
  28. }

Client Use

This repo also provides two client libraries browser and io that extend the baseangel_client interface, and allow you to use a very similar API on the client to that ofthe server.

The provided clients also automatically try to reconnect their WebSockets when disconnected,which means you can restart your development server without having to reload browser windows.

They also provide streams of data that pump out filtered data as it comes in from the server.

Clients can even perform authentication over WebSockets.

In the Browser

  1. import "package:angel_websocket/browser.dart";
  2.  
  3. main() async {
  4. Angel app = new WebSockets("/ws");
  5. await app.connect();
  6.  
  7. var Cars = app.service("api/cars");
  8.  
  9. Cars.onCreated.listen((car) => print("New car: $car"));
  10.  
  11. // Happens asynchronously
  12. Cars.create({"brand": "Toyota"});
  13.  
  14. // Authenticate a WebSocket, if you were not already authenticated...
  15. app.authenticateViaJwt('<some-jwt>');
  16.  
  17. // Listen for arbitrary events
  18. app.on['custom_event'].listen((event) {
  19. // For example, this might be sent by a
  20. // WebSocketController.
  21. print('Hi!');
  22. });
  23. }

CLI Client

  1. import "package:angel_framework/common.dart";
  2. import "package:angel_websocket/io.dart";
  3.  
  4. // You can include these in a shared file and access on both client and server
  5. class Car extends Model {
  6. int year;
  7. String brand, make;
  8.  
  9. Car({this.year, this.brand, this.make});
  10.  
  11. @override String toString() => "$year $brand $make";
  12. }
  13.  
  14. main() async {
  15. Angel app = new WebSockets("/ws");
  16.  
  17. // Wait for WebSocket connection...
  18. await app.connect();
  19.  
  20. var Cars = app.service("api/cars", type: Car);
  21.  
  22. Cars.onCreated.listen((Car car) {
  23. // Automatically deserialized into a car :)
  24. //
  25. // I just bought a new 2016 Toyota Camry!
  26. print("I just bought a new $car!");
  27. });
  28.  
  29. // Happens asynchronously
  30. Cars.create({"year": 2016, "brand": "Toyota", "make": "Camry"});
  31.  
  32. // Authenticate a WebSocket, if you were not already authenticated...
  33. app.authenticateViaJwt('<some-jwt>');
  34. }