DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Buildpacks: An Open-Source Alternative to Chainguard
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Java Container Application Memory Analysis
  • Using Spring To Download a Zip File, Extract It, and Upload It to Cloud Storage Without Storing Files Locally in the Container

Trending

  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • Understanding Java Signals
  • How to Format Articles for DZone
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Java Websocket Containers: The Possibilities

Java Websocket Containers: The Possibilities

With the Java Websocket API being integrated directly into Java EE7, check out how Tyrus, the reference implementation, integrated with containers for maximum effect.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
Jun. 21, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.3K Views

Join the DZone community and get the full member experience.

Join For Free

The Java Websocket API (JSR 356) specification supports different containers:

  • Good old Java EE 7 app servers – since Websocket API is integrated directly into the Java EE 7 Platform.
  • Servlet 3.1 containers.
  • Standalone containers – for runtimes which are not servlet compliant.

Hello Tyrus!

Tyrus is the reference implementation for the Java Websocket API.

  • What’s important to understand is that it’s the implementation of the Websocket specification (i.e. it provides both Server and Client side support for building Websocket applications using the standard JSR 356 APIs).
  • It’s not an out-of-the-box container (i.e. it does not have a runtime as such).

So, How Does Tyrus Support the Above-Mentioned Runtimes?

Here is how:

  • Tyrus has a modular architecture (i.e. it has different modules for server and client implementations, an SPI, etc.).
  • It has the concepts of containers (you can think of them as connectors) for specific runtime support (these build on the modular setup).

Tyrus Containers

Servlet Container a.k.a Tyrus-container-servlet

  • Used to integrate with existing Servlet 3.1 containers.
  • Leveraged to plug into the Web (Servlet) Container in Java EE 7 compliant app servers.

Standalone container

You have two options:

Grizzly Container (tyrus-container-grizzly module)

  • This is achieved with Grizzly (which provides the runtime).
  • It can be used for server or client (or both) modes as per your requirements.

Here are the Maven dependencies:

...
<dependencies>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-server</artifactId>
            <version>1.12</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-grizzly-server</artifactId>
            <version>1.12</version>
        </dependency>
</dependencies>
...

Here is the Websocket (annotated) endpoint:

//imports ommitted

@ServerEndpoint("/testwsep")
public class MyWsendpoint {

    static Set<Session> clients = new HashSet<Session>();

    @OnOpen
    public void open(Session s) {
        clients.add(s);
    }

    @OnMessage
    public void msg(String m) {
        for (Session client : clients) {
            try {
                client.getBasicRemote().sendText("Catch this! "+ m);
            } catch (IOException ex) {
                Logger.getLogger(MyWsendpoint.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
//.. other callback methods ommitted - @onClose, @onError
}

Here is how to start it (embedded):

public class TyrusGrizzlyWebsocketRunner {

    public static void main(String[] args) throws DeploymentException, IOException, InterruptedException {
        Server server = new Server("localhost", 8080, "", null, MyWsendpoint.class);
        server.start();
        System.out.print("---- Server Started -----");
        new CountDownLatch(1).await();
    }
}

Pure JDK container (tyrus-container-jdk-client module)

  • Client only mode.
  • Vanilla JDK (i.e. no additional dependencies).
  • Leverages JDK 1.7 non-blocking I/O (Asynchronous Channel).

Maven dependencies:

<dependencies>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-client</artifactId>
            <version>1.12</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.tyrus</groupId>
            <artifactId>tyrus-container-jdk-client</artifactId>
            <version>1.12</version>
        </dependency>
</dependencies>

The (annotated) client endpoint:

@ClientEndpoint
public class WebsocketAnotatedClient {

    @OnOpen
    public void onopen(){
        System.out.println("connected to server.... ");
    }

    @OnMessage
    public void onmsg(String msg){
        System.out.println("recieved from server.... "+ msg);
    }
}

Client code to connect to Websocket endpoint (outlined above):

public class WebsocketClientOnVaniallJDKRunner {

    public static void main(String[] args) throws DeploymentException, IOException, InterruptedException {
        WebSocketContainer cc = ContainerProvider.getWebSocketContainer();
        Session connectToServer = cc.connectToServer(WebsocketAnotatedClient.class, URI.create("ws://localhost:8080/testwsep"));

        new CountDownLatch(1).await();
    }

}

References

  • Tyrus modules
  • Tyrus javadocs
  • JSR 356 (Websocket) specification

Cheers!

Container Java (programming language) WebSocket

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Buildpacks: An Open-Source Alternative to Chainguard
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Java Container Application Memory Analysis
  • Using Spring To Download a Zip File, Extract It, and Upload It to Cloud Storage Without Storing Files Locally in the Container

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!