How it works...

The first important thing in our server is this annotation:

@Singleton

Of course, we must ensure that we have one and only one instance of the server endpoint. This will ensure that all peers are managed under the same umbrella.

Let's move on to talk about peers:

private final List<Session> peers = Collections.synchronizedList(new ArrayList<>());

The list holding them is a synchronized list. This is important because you will add/remove peers while iterating on the list, so things could be messed up if you don't protect it.

All the default websocket methods are managed by the application server:

@OnOpenpublic void onOpen(Session peer){    peers.add(peer);}    @OnClosepublic void onClose(Session peer){    peers.remove(peer);}    @OnError ...

Get Java EE 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.