@WebSocketClient in GlassFish 4 (TOTD #204)

Guest Author

Tyrus is the Reference
Implementation for Java API for WebSocket (JSR 356) and is already
integrated in href="http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/latest-glassfish.zip">GlassFish
4. The implementation is rapidly evolving and and adding
support for different features already defined in the href="http://java.net/projects/websocket-spec/downloads/download/Spec%20javadoc%20Drafts/v012/JavaWebSocket_JSR356_012.pdf">latest
version of the specification.

The latest integration in GlassFish added support for creating
Java-based WebSocket clients.

Any POJO can be made a WebSocket client by adding @WebSocketClient.
A inbound message is received in a method annotated with @WebSocketMessage.
Any method can be designated as lifecycle method by specifying @WebSocketOpen,
@WebSocketClose, @WebSocketError. Here is
a simple sample:

public class MyClient {
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getRemote());
try {
} catch (IOException ex) {
Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);

public void processMessage(String message, Session session) {
System.out.println(getClass().getName() + ": " + message);

In this code, a message is sent to the connected WebSocket endpoint
whenever the connection is initiated. An inbound message (coming
from the server) is processed using processMessage

The endpoint code is pretty trivial:

@WebSocketEndpoint(value="/websocket", configuration=DefaultServerConfiguration.class)
public class MyEndpoint {

public String sayHello(String name) {
System.out.println(getClass().getName() + ": " + name);
return "Hello " + name;


The endpoint has a single method that receives the payload, appends
a string and returns back as the response. Even though server is
returning the response right away, the client views this as two
separate messages, one outbound and the other one inbound. So any
message-exchange-pattern such as request/response need to be
specifically built using the application code. The configuration
attribute, in this case, is optional and will be fixed in a
subsequent release of Tyrus.

The client can bootstrap using Java SE or Java EE components as:

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
container.connectToServer(MyClient.class, URI.create(uri));

The complete source code used in this Tip Of The
Day (TOTD) is href="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/File/0a9a9479da26a0ddae89288c06233f49/totd204_client.zip">available
here. It will run on the latest href="https://blogs.oracle.com/arungupta/entry/how_to_checkout_and_build">checked
out version of GlassFish workspace, not a promoted build yet
(bleeding edge eh ;-)

Please provide feedback on href="http://java.net/projects/tyrus/lists/users/archive">users@tyrus.java.net.

How are you going to use Java-based WebSocket client in your
applications ?

Here are other Java EE 7 entries published on this blog so far:

  • Create ManagedExecutorService,
    ManagedScheduledExecutorService, ManagedThreadFactory,
    ContextService in GlassFish 4 build 74 (href="https://blogs.oracle.com/arungupta/entry/create_managedexecutorservice_managedscheduledexecutorservice_managedthreadfactory_contextservice">TOTD

  • Resource Library Contracts in JSF 2.2 (href="https://blogs.oracle.com/arungupta/entry/resource_library_contracts_in_jsf2">TOTD
  • Java EE 7 Maven Archetype - Available in NetBeans (href="https://blogs.oracle.com/arungupta/entry/java_ee_7_maven_archetype">TOTD
  • Java EE 7 and NetBeans IDE - Early Support Available (href="https://blogs.oracle.com/arungupta/entry/java_ee_7_and_netbeans">TOTD
  • JSF 2.2 FacesFlow - @FlowScoped, #{flowScope}, @FlowDefinition
  • Java EE 7 Maven Application (href="https://blogs.oracle.com/arungupta/entry/java_ee_7_maven_application">TOTD
  • Default Data Source in Java EE 7: Lesser XML and More Defaults
  • JPA 2.1 Implementation - EclipseLink M6 integrated in
    GlassFish 4 (href="https://blogs.oracle.com/arungupta/entry/jpa_2_1_implementation_eclipselink">TOTD
  • JAX-RS Client API and GlassFish 4 - Logging HTTP Messages (href="https://blogs.oracle.com/arungupta/entry/jax_rs_client_api_and">TOTD
  • JAX-RS Custom Entity Providers (href="https://blogs.oracle.com/arungupta/entry/jax_rs_custom_entity_providers">TOTD
  • Batch Applications in Java EE 7 (href="https://blogs.oracle.com/arungupta/entry/batch_applications_in_java_ee">TOTD

  • Simple
    JMS 2.0 Sample (href="https://blogs.oracle.com/arungupta/entry/simple_jms_2_0_sample">TOTD
  • href="https://blogs.oracle.com/arungupta/entry/what_s_new_in_servlet">What's
    in Servlet 3.1 ?
  • href="https://blogs.oracle.com/arungupta/entry/concurrency_utilities_for_java_ee">Concurrency
    for Java EE (JSR 236)
  • Collaborative
    Whiteboard using WebSocket in GlassFish 4 (href="https://blogs.oracle.com/arungupta/entry/collaborative_whiteboard_using_websocket_in">TOTD
  • Non-blocking
    I/O using Servlet 3.1 (href="https://blogs.oracle.com/arungupta/entry/non_blocking_i_o_using">TOTD
  • href="https://blogs.oracle.com/arungupta/entry/what_s_new_in_ejb">What's
    in EJB 3.2 ?
  • JPA
    2.1 Schema Generation (href="https://blogs.oracle.com/arungupta/entry/jpa_2_1_schema_generation">TOTD
  • href="https://blogs.oracle.com/arungupta/entry/websocket_applications_using_java_jsr">WebSocket
    using Java (JSR 356)
  • Jersey
    2 in GlassFish 4 (href="https://blogs.oracle.com/arungupta/entry/jersey_2_in_glassfish_4">TOTD
  • WebSocket
    and Java EE 7 (href="https://blogs.oracle.com/arungupta/entry/websockets_and_java_ee_7">TOTD
  • href="https://blogs.oracle.com/arungupta/entry/json_p_java_api_for">Java
    for JSON Processing (JSR 353)
  • href="https://blogs.oracle.com/arungupta/entry/jms_2_0_early_draft">JMS
    Early Draft (JSR 343)

Join the discussion

Comments ( 4 )
  • Hal Thursday, February 14, 2013

    And there was much rejoicing

  • guest Friday, February 15, 2013

    I've been waiting for this a few months now! Thanks for letting us know it's coming. And the classes for the Java client are also in Tyrus?

    Does Netbeans7.3 know how to handle these annotations yet?

    I presume once we get a connection to the server we can connect to the ejb container as if using a local connection?

    How would secure communications change your basic code? It's not too realistic that websocket will be used to connect to a localhost! Most of us write clients that will be connecting to a remote host.

    Thanks a bunch for keeping us informed about the Java client for websocket.

  • Arun Gupta Friday, February 15, 2013

    All the classes are in Tyrus and integrated in GlassFish.

    NetBeans Development Version provide early support for Java EE 7 and is explained at:


    Now this is bleeding edge, there is not even a promoted build to support this. So feel free to check out support in the IDE :-)

    I will play with connection to remote host and then push that as a blog. EJBs should be accessible and thats for another blog entry :)

    How do you plan to use this feature ?

  • guest Friday, February 15, 2013

    My plan is to modernize my financial applications. I've been using RMI for 15 years and at the time I started I had to write everything for myself. If there were any free containers for learning I was unaware of them. Now, however, I want to start using the JEE ejb container to interface with my database and feed the data to my clients. Websockets "sounds" like it offers a great 2-way communication facility to create first rate clients. I cannot feature a day when I could conscionably ask my internal users to attempt to get their daily work done with something as crude as a browser. So I'm very interested in anything that modernizes java clients to use the facilities of JEE.

    Please tell your friends over at Glassfish to work on the documentation regarding how to connect a Java client to a remote server including secure communications! Nobody needs to connect a java client to a local server in the real world!!! Thanks.

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.