Asynchronous connectToServer

Posted by Pavel Bucek on Oracle Blogs See other posts from Oracle Blogs or by Pavel Bucek
Published on Mon, 4 Nov 2013 15:32:20 +0000 Indexed on 2013/11/04 22:03 UTC
Read the original article Hit count: 425

Filed under:

Users of JSR-356 – Java API for WebSocket are probably familiar with WebSocketContainer#connectToServer method. This article will be about its usage and improvement which was introduce in recent Tyrus release.

WebSocketContainer#connectToServer does what is says, it connects to WebSocketServerEndpoint deployed on some compliant container. It has two or three parameters (depends on which representation of client endpoint are you providing) and returns aSession. Returned Session represents WebSocket connection and you are instantly able to send messages, register MessageHandlers, etc.

An issue might appear when you are trying to create responsive user interface and use this method – its execution blocks until Session is created which usually means some container needs to be started, DNS queried, connection created (it’s even more complicated when there is some proxy on the way), etc., so nothing which might be really considered as responsive. Trivial and correct solution is to do this in another thread and monitor the result, but.. why should users do that? :-) Tyrus now provides async* versions of all connectToServer methods, which performs only simple (=fast) check in the same thread and then fires a new one and performs all other tasks there. Return type of these methods is Future<Session>.

List of added methods:

As you can see, all connectToServer variants have its async* alternative. All these methods do throw DeploymentException, same as synchronous variants, but some of these errors cannot be thrown as a result of the first method call, so you might get it as the cause ofExecutionException thrown when Future<Session>.get() is called.

Please let us know if you find these newly added methods useful or if you would like to change something (signature, functionality, …) – you can send us a comment to [email protected] or ping me personally.

Related links:

© Oracle Blogs or respective owner

Related posts about /Oracle