{{announcement.body}}
{{announcement.title}}

Code Play #1: WebSockets With Vert.x and Angular

DZone 's Guide to

Code Play #1: WebSockets With Vert.x and Angular

In the first article in the Code Play Series, we take a look at using websockets to create a real time, multiuser canvas.

· Web Dev Zone ·
Free Resource

This is the first of the series of Code Play where I will be dabbling with tech I've not had much chance to get deep into.

Looking around various web-socket libraries, I wanted something quick and easy to get up and running that could handle some complex eventing. Vert.x and Angular seemed a nice combination and will be used to make an app that communicates via web-sockets and the vert.x event bus. To make this a little more exciting, there will be an array of HTML canvas's that will display what other people are drawing in real time:

Real-time drawing

How this works is when somebody hits the URL, they add their name and get added to a drawing session. A canvas will be displayed for each person, when they draw on the left panel it will update the corresponding panel on the right and everybody then see's it.

A simple canvas was created that will be used to display the drawing points. On its own, it doesn't actually do anything other than expose a single method to update the canvas with the drawing points

<canvas #canvas width="320" height="480" style="border:2px solid;"></canvas> 

JavaScript
 




x
1
44


 
1
export class DrawCanvasComponent implements OnInit {
2
 
          
3
  @ViewChild('canvas', { static: true }) _canvas;
4
  canvas;
5
  ctx;
6
 
          
7
  pos = { x: 0, y: 0 };
8
 
          
9
  constructor() { }
10
 
          
11
  ngOnInit() {
12
    this.canvas = this._canvas.nativeElement;
13
    this.ctx = this.canvas.getContext('2d');
14
  }
15
 
          
16
  update(drawing: DrawingStroke) {
17
    if (drawing.type === 'draw') {
18
      this.draw(drawing);
19
    } else {
20
      this.setPosition(drawing);
21
    }
22
  }
23
 
          
24
  private setPosition(position: DrawingStroke) {
25
    this.pos.x = position.x;
26
    this.pos.y = position.y;
27
  }
28
 
          
29
  private draw(e: DrawingStroke) {
30
    this.ctx.beginPath();
31
 
          
32
    this.ctx.lineWidth = 5;
33
    this.ctx.lineCap = 'round';
34
    this.ctx.strokeStyle = '#c0392b';
35
 
          
36
    this.ctx.moveTo(this.pos.x, this.pos.y); // from
37
    this.setPosition(e);
38
 
          
39
    this.ctx.lineTo(this.pos.x, this.pos.y); // to
40
 
          
41
    this.ctx.stroke(); // draw it!
42
  }
43
 
          
44
}



Capturing the Drawing Points

A wrapper component will use the drawing canvas to capture all the click events:

HTML
JavaScript
 




xxxxxxxxxx
1
29


1
export class DrawCanvasEventComponent implements OnInit {
2
 
          
3
  @Output() drawEvent = new EventEmitter<DrawingStroke>();
4
 
          
5
  @ViewChild(DrawCanvasComponent, { static: true }) _canvasWrapper: DrawCanvasComponent;
6
  canvasWrapper: DrawCanvasComponent;
7
  canvas;
8
  ctx;
9
  offset;
10
  sentCount = 0;
11
 
          
12
  pos: PostionEvent = { x: 0, y: 0 };
13
 
          
14
  count = 0;
15
 
          
16
  constructor() { }
17
 
          
18
  ngOnInit() {
19
    this.canvasWrapper = this._canvasWrapper;
20
    this.canvas = this.canvasWrapper._canvas.nativeElement;
21
    this.ctx = this.canvas.getContext('2d');
22
    this.canvas.addEventListener('mousemove', this.draw.bind(this));
23
    this.canvas.addEventListener('mousedown', this.setPosition.bind(this));
24
    this.canvas.addEventListener('mouseup', this.setPosition.bind(this));
25
 
          
26
    this.canvas.addEventListener('touchmove', this.draw.bind(this));
27
    this.canvas.addEventListener('touchstart', this.setPosition.bind(this));
28
    this.canvas.addEventListener('touchend', this.setPosition.bind(this));
29
  }
30
}


The event listeners capture mouse movements and touch is for mobile gestures. These then eventually call the update on the canvas component above via the @ViewChild method. Also when these events occur they use the EventEmitter to emit the event using the @Output method.

Setting Up The Socket Client Side

Vert.x utilizes SockJs to do it bidding but is wrapped up in the vertx3-eventbus-client. This allows easy utilization of web-sockets. A service was created that opens up the web-socket and connects the Java vert.x back end.

JavaScript
 




x


1
@Injectable({
2
  providedIn: 'root'
3
})
4
export class EventbusService {
5
  private _eventBus: EventBus;
6
  eventBus = new BehaviorSubject(null);
7
 
          
8
  private meetingGuid;
9
 
          
10
  constructor(
11
  ) {
12
    this.init();
13
  }
14
 
          
15
  init() {
16
    this._eventBus = new EventBus(environment.eventBus);
17
    this._eventBus.onopen = () => {
18
      this.eventBus.next(this._eventBus);
19
    };
20
  }
21
 
          
22
}


One the connection is established, the onopen event will be fired simple! A BehaviourSubject was used here so that any components can use the connection even after is has been established or to avoid the scenario where there is no connection yet.

A DrawEventbusService was created to make use of this event bus service and do only draw tasks events:

JavaScript
 




xxxxxxxxxx
1
27


1
export class DrawEventbusService {
2
 
          
3
  private serverToClient = 'server.to.client.';
4
  private clientToServer = 'client.to.server.';
5
 
          
6
  constructor(
7
    private eventBusService: EventbusService
8
  ) { }
9
 
          
10
 
          
11
  hostDrawingSession(user: User, eventHandlers: DrawEventbusEventHandlers) {
12
    this.getEventBus()
13
      .subscribe(eventBus => this.init(eventBus, user, eventHandlers));
14
  }
15
 
          
16
  joinDrawingSession(user: User, eventHandler: DrawEventbusEventHandlers['onDrawEvent']) {
17
    this.getEventBus()
18
      .subscribe(eventBus => { this.initDrawGuest(eventBus, user, eventHandler) });
19
  }
20
 
          
21
  sendEvent(id: string, command: string, event: any) {
22
    event.command = command
23
    event.meetingUUID = id;
24
    this.getEventBus().subscribe(eventBus => {
25
      eventBus.send(this.clientToServer + id, event);
26
    });
27
  }
28
 
          
29
  private getEventBus() {
30
    return this.eventBusService.eventBus
31
      .pipe(
32
        filter(eb => eb !== null)
33
      );
34
  }
35
}


As seen earlier, the main event bus is subscribed to and the pipe function is used to filter the initial null in the behaviour subject.

For the app the work there are 3 main interactions utilising the web-socket connection:

  • host drawing session - this is used to create the drawing session
  • join drawing session - when a user wants to join a session
  • send event - used pass canvas draw events 

Notice the client and server variables, these are outbound and inbound paths that are used in the backend in the socket handler that allow data to be sent down these channels.

Setting up The Socket Server-Side

Vert.x has a concept of 'verticles' and instead of using a traditional technique of controller -> service -> repository, the back-end has been split into verticles of logic; separation of concerns. These verticles will make use of the Vert.x event bus to communicate between each other. This looks something like:

Verticles infrastructure

The backend has 4 main verticles

  • web socket - set's up  SockJs and the routing mechanisms
  • repository - the data store
  • creator (events) - initialises events and listeners
  • draw events - handles the events from the user and publishes the response

The WebSocketVerticl class will set up the what's called the bridge and the is the part that does the linking between front and backend. Here the SockJs bridge is configured.

Java
 




x


1
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
2
sockJSHandler.bridge(getBridgeOptions());
3
 
          
4
private BridgeOptions getBridgeOptions() {
5
  return new BridgeOptions()
6
    .addOutboundPermitted(
7
    new PermittedOptions().setAddressRegex(config.getServerToClient() + "\\.[a-z-0-9]{36}"))
8
    .addInboundPermitted(
9
    new PermittedOptions().setAddressRegex(config.getClientToServer() + "\\.[a-z-0-9]{36}"))
10
    .addInboundPermitted(new PermittedOptions().setAddressRegex(config.getClientToServer() + "\\.new"));
11
    }



There are 2 config params getServerToClient = 'server.to.client' and getClientToServer = 'client.to.server'. The BridgeOptions are made up of 3 addresses — 1 outbound and 2 inbound. These are the channels that the app communicates along and checked through a regular expression where,[a-z-0-9]{36} is a very loose UUID match. The resulting communication channel take the form of

  • server.to.client.6bd9e48d-4d03-4b20-ad1f-6ce7b9241128 - Outbound
  • client.to.server.6bd9e48d-4d03-4b20-ad1f-6ce7b9241128 - Inbound
  • client.to.sever.new - Inbound

When shown how to send messages these channels will become more apparent.

The next step was to add the SockJs config to a route. So when the client creates the vert.x EventBus object under the hood it will call <host>/eventbus/info?t=1595234808993

Java
 




xxxxxxxxxx
1


 
1
Router router = Router.router(vertx);
2
router.route("/eventbus/*")
3
  .handler(sockJSHandler)
4
  .failureHandler(error -> log.error("error {}", error));


In addition to the routing the Angular app also needs to be added hooked up. Note: the web files are set in java/resources/webroot

Java
 




x




1
router.route().handler(StaticHandler.create()
2
                       .setCachingEnabled(false)
3
                       .setIndexPage("/index.html"));
4
router.routeWithRegex("\\/.+").handler(context -> {
5
  context.reroute("/index.html");
6
});


Finally hooking these all together will result in the web-socket and routes configured and ready to run with the server listening on the define port.

Java
 




x




1
vertx.createHttpServer()
2
  .requestHandler(router)
3
  .listen(config.getPort(), this::httpServerResult);



The WebSocketRepositoryVerticle simply consumes the event-bus and has handlers for new session and new guests. 

Java
 




xxxxxxxxxx
1


 
1
@Override
2
public void start() {
3
  vertx.eventBus().consumer(Commands.newDrawing, this::newDrawing);
4
  vertx.eventBus().consumer(Commands.newDrawGuest, this::newDrawGuest);
5
}


For persistence, the app utilizes the vert.x shared data which is a Map of types. An example of getting the data, where matched by id, fetches the map with the object drawState as the key for the value, then parses it to the DrawState object

Java
 




xxxxxxxxxx
1
15


1
    private Optional<DrawState> getDrawState(String id) {
2
        LocalMap<String, String> drawSession = vertx.sharedData().getLocalMap(id);
3
        return Optional.of(drawSession)
4
                .filter(q -> !q.isEmpty())
5
                .map(this::convertToDrawState);
6
    }
7
    
8
    private DrawState convertToDrawState(LocalMap<String, String> stringLocalMap) {
9
        try {
10
            return Json.decodeValue(stringLocalMap.get("drawState"), DrawState.class);
11
        } catch (Exception e) {
12
            log.error("error {}", e);
13
            throw new RuntimeException("failed to parse");
14
        }
15
    }



At this point, the server will run but no events are setup that are listening to anything, now enter WebSocketEventHandler.

From above, the client.to.server.new handler is set here, anytime this is called from the client a new draw session will get sent the repository and new listeners setup for draw events.

Java
 




x


1
// message body: {"id":"85a3e1ab-a4c7-4409-aa34-dcf1e3dc73bd","name":"Dale","host":true}
2
private void createDrawingListener() {
3
  vertx.eventBus().consumer(config.getClientToServer() + ".new")
4
    .handler(message -> {
5
      var body = new JsonObject(message.body().toString());
6
      var drawId = body.getString("id");
7
      
8
      createDrawing(message, body);
9
      
10
      createListeners(drawId);
11
    });
12
}


The createListeners(drawId) then set up the listening channel. The drawId is the ID of the session. This means that any events coming through the matching channel (eg. client.to.server.6bd9e48d-4d03-4b20-ad1f-6ce7b9241128) will get passed on to the draw event listener via the Commands.drawEvent channel

Java
 




x



1
  private void createListeners(String drawId) {
2
        vertx.eventBus().consumer(config.getClientToServer() + "." + drawId,
3
                event -> {
4
                    vertx.eventBus().send(Commands.drawEvent, event.body().toString());
5
                });
6
    }


Finally, the message will get picked up in the DrawEventVerticle where it will be processed by the draw event case and broadcast to all the clients using the outbound address that clients are listening on. The second case, newDrawGuest, will simply return extra data to help initialize the front end.

Java
 




x


1
@Override
2
public void start() {
3
  vertx.eventBus().consumer(Commands.drawEvent, this::drawEvent);
4
}
5
 
          
6
private void drawEvent(Message message) {
7
  var body = new JsonObject(message.body().toString());
8
  var drawId = body.getString("meetingUUID");
9
 
          
10
  switch (getCommand(body)) {
11
    case Commands.drawEvent:
12
      //{"x":239,"y":279,"type":"draw","userUUID":"1bacde6c-9e54-4692-8c98-d89db49c05df","command":"draw-event","meetingUUID":"1bacde6c-9e54-4692-8c98-d89db49c05df"}
13
      vertx.eventBus().publish(config.getServerToClient() + "." + drawId, body.toString());
14
      break;
15
    case Commands.newDrawGuest:
16
      // {"id":"a48ff5b2-57be-46ed-9ce8-8e6edbf67a2b","meetingUUID":"966bfc99-5bff-4503-8216-6efb64852d9d","host":false,"name":"bill","command":"new-draw-guest"}
17
      vertx.eventBus().request(Commands.newDrawGuest, body.toString(), event -> {
18
        var send = body.put("drawState", event.result().body()).toString();
19
        vertx.eventBus().publish(config.getServerToClient() + "." + drawId, send);
20
      });
21
      break;
22
  }
23
}


Now the app would work and the drawn events will do a round robin trip from the left drawing canvas, to the server and back via web socket to right hand socket grid - same as the image at the top.

The Drawing Grid

To display all the drawing canvases of each person in the UI the canvas had a new wrapper around it that contains an rxjs Subject this simply allows it to be passed events and on subscribe, call the update function in the drawing canvas via @ViewChild

JavaScript
 




x


 
1
export class DrawingUpdaterComponent implements OnInit {
2
 
          
3
@Input() attendee: User;
4
@Input() drawEvent: Subject<DrawingStroke>;
5
 
          
6
@ViewChild(DrawCanvasComponent, { static: true }) canvas: DrawCanvasComponent;
7
 
          
8
  constructor(
9
    private drawService: DrawService
10
  ) { }
11
 
          
12
  ngOnInit() {
13
    this.drawEvent
14
      .pipe(
15
        filter(x => x !== null)
16
      )
17
      .subscribe((drawingStroke: DrawingStroke) => {
18
        this.canvas.update(drawingStroke);
19
      });
20
  }
21
}


The next step is to setup a listener that will add a new canvas to the UI when somebody joins and then also update their canvas when they draw.

The draw grid template is as simple as:

HTML
 




xxxxxxxxxx
1


1
<div class="drawings-wrapper">
2
    <div #drawingList></div>
3
</div>


Every time a new person joins they will be added via:

JavaScript
 




xxxxxxxxxx
1


 
1
  @ViewChild('drawingList', { static: false, read: ViewContainerRef }) drawGrid: ViewContainerRef;


and injected using the Angular componentFactoryResolver. Notice the subject being passed in - this will be used to update the canvas.

JavaScript
 




x


1
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DrawingUpdaterComponent);
2
const cmpRef = this.drawGrid.createComponent(componentFactory);
3
    cmpRef.instance.attendee = attendee;
4
    cmpRef.instance.drawEvent = subject;


Each time a user is added to the session they are also added to a list of Subject's, the same subject passed into the component:

JavaScript
 




xxxxxxxxxx
1


 
1
interface DrawSubject {
2
  [index: string]: Subject<DrawingStroke>
3
}
4
 
          
5
attendeesInList: DrawSubject = {};
6
 
          


So now, when listening for draw events, these are then picked up, process and update the matching subject:

JavaScript
 




xxxxxxxxxx
1
13


 
1
listenForDrawEvents() {
2
  this.drawService.drawEvent
3
    .pipe(
4
    filter(x => x !== null)
5
  )
6
    .subscribe((event: any) => {
7
 
          
8
      if (event['command'] === 'draw-event') {
9
 
          
10
        this.attendeesInList[event.userUUID].next(event);
11
 
          
12
      }
13
}


So now anytime a draw event comes in it will update the subject and it turn update the canvas.

This was a simple use case and sending an event to the server via sockets is as simple as

JavaScript
 




x


 
1
 this.getEventBus().subscribe(eventBus => {
2
   eventBus.send(this.clientToServer + id, {some: 'object'});
3
 });



Afterthoughts

Event-Driven

I kind of like setting up the backend as verticles instead of creating a typical controller -> service -> repository technique. I can see the benefit of having these loosely coupled in that extra processing could be done by subscribing to the events. Also that these could scale quite well for the events handlers for example. What i did find was that it was a little harder to see where it went after the event bus publish. But searching for the channel names found the destinations. 

Web Sockets

This came as a breeze as there was so little setup. It was like sockets weren't being used at all. The event bus also simplifies the process. There are also many events, using vert.x, that can be hooked into when a socket connection is established such as connected, event, disconnect, etc. There are also security mechanisms for authentication available so it's not wide open. I was also tinkering of the thought of replacing APIs with sockets? It would seem the right thing to do for low latency super fast events but not for standard rest calls /user etc. I also did not find a nice way to create some structure to the payload, it forces you to add an identifier such as 'command' or 'action' that would end up going into an if or case statement on the server when processing it. As with rest you already have PUT / POST etc

Speed

Some counters were added to see the number of event/calls to the server. After a 2 second 'squiggle' it can easily be 80 calls to the server and it updates the grid canvas pretty much instantly. I did an experiment and uploaded this to Heroku and asked my team to log on and see what happened. Around 10 were drawing, 1000's of event per second going to my and their screen all at the same time with hardly any lag, was pretty cool.

Conclusion

I liked using this combination of vert.x and the event bus for web-socket communication. It was fast, easy and comes with nice features like auto-reconnect and security. Along with the toolkit vert.x comes with, it can do nearly everything modern apps need to do and its reactive. A minor pain point was I struggled to find a nice solution when issuing events and how they are identified in the backend compared to rest where the url and request type map to a function. Angular helped with the rxjs eventing easily updating components. All in all a nice bit of fun to experiment with.

Hope you enjoyed the first episode of the Code Play series.

You can find and run the full example on GitHub.

Topics:
angular, canvas, java, vert.x, websocket

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}