Async client

The asynchronous client manages the same messages of the basic client but it:

  • Doesn't suspend the current thread until the sending of the message
  • Can establish a send timeout. After this time, the message expires
  • Can batch the messages

Here you can see how to take the asynchronous client:

Async async = sessionClient.getAsyncRemote();

See some examples of text, binary, and object messages:

ByteBuffer byteBuffer = allocate(11); 
Future<Void> future = async.sendBinary(byteBuffer);
async.setSendTimeout(45);
future.get();

To send asynchronous messages, the java.util.concurrent. Future class introduced in Java 7 is used. In this sample, the message will be sent after the execution of the get() method of the Future class.

Facultatively, we can set the timeout, so after that the message expires and it cannot be sent. If the timeout is set to -1, then it is disabled.

In the previous section, Container configuration, we exposed the default timeouts. This last configuration of the timeout is used to override the default.

The alternative to the Future class is the SendHandler:

ByteBuffer byteBuffer = allocate(39);
SendHandler sendHandler = new SendHandler() {
@Override
public
void onResult(SendResult result) {
boolean ok = result.isOK();
Throwable throwable = result.getException();
}
};
async.sendBinary(byteBuffer, sendHandler);

The javax.websocket.SendHandler provides a callback method where you can see the status of the result. You can see if the send result is okay. If not, you can monitor it through the thrown exception. The same thing can be done with the text and object messages:

future = async.sendObject(666);
future.get();
...
async.setSendTimeout(45);
async.sendObject("my test 2", sendHandler);
future = async.sendText("my text");
future.get();
...
async.sendText("my text 2", sendHandler);

Another important feature is the batch. With the batch we can declare all the objects, texts or binaries to send them all together as they are in a transaction. Here is a sample of a send batch:

async.setBatchingAllowed(true);
async.sendObject("my test 2", sendHandler);
async.sendText("my text 2", sendHandler);
future = async.sendText("my text");
future.get();
async.flushBatch();

If we set the setBatchingAllowed method to true, then all those messages will be sent only when the flushBatch() method is executed. If there is an error, all messages will be terminated.

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

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