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:

@OnOpen
public void onOpen(Session peer){
peers.add(peer);
}

@OnClose
public void onClose(Session peer){
peers.remove(peer);
}

@OnError
public void onError(Throwable t){
System.err.println(t.getMessage());
}

@OnMessage
public void onMessage(String message, Session peer){
peers.stream().filter((p) -> (p.isOpen())).forEachOrdered((p) ->
{
p.getAsyncRemote().sendText(message + " - Total peers: "
+ peers.size());
});
}

Also, let's give a special mention to the code on our onMessage method:

    @OnMessage
public void onMessage(String message, Session peer){
peers.stream().filter((p) -> (p.isOpen())).forEachOrdered((p)
-> {
p.getAsyncRemote().sendText(message + " - Total peers: "
+ peers.size());
});
}

We are sending a message to the peer only if it is open.

Now looking to our client, we have a reference to the server URI:

private final String asyncServer = "ws://localhost:8080/
ch10-async-websocket/asyncServer";

Note that the protocol is ws, specific to websocket communication.

Then, we have a method to open the connection with the server endpoint:

public void connect() {
WebSocketContainer container =
ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(this, new URI(asyncServer));
} catch (URISyntaxException | DeploymentException | IOException ex) {
System.err.println(ex.getMessage());
}
}

And once we have the message confirmation from the server, we can do something about it:

@OnMessage
public void onMessage(String message, Session session) {
response.resume(message);
}

This response will appear on the endpoint that is calling the client:

@GET
public void asyncService(@Suspended AsyncResponse response){
AsyncClient client = new AsyncClient(response);
client.connect();
client.send("Message from client " + new Date().getTime());
}

We are passing the reference to the client so the client can use it to write the message on it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.126