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
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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • A Systematic Approach for Java Software Upgrades
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • DZone's Article Submission Guidelines
  • Understanding the Circuit Breaker: A Key Design Pattern for Resilient Systems
  • AI Agent Architectures: Patterns, Applications, and Implementation Guide
  • Before You Microservice Everything, Read This
  1. DZone
  2. Coding
  3. Java
  4. Programmatic Websocket Endpoints in Java EE 7

Programmatic Websocket Endpoints in Java EE 7

The Java Websocket API is versatile. In this 2-step post, you'll learn how to develop and deploy websocket endpoints.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
Jan. 06, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
16.5K Views

Join the DZone community and get the full member experience.

Join For Free

This post briefly demonstrates how to develop and deploy (server and client) websocket endpoints using the programmatic version of the Java Websocket API.

Step #1 - Extend the javax.websocket.Endpoint Class

public class ProgrammaticEchoEnpoint extends Endpoint {

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("Peer " + session.getId() + " connected");
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String message) {
                try {
                    session.getBasicRemote().sendText("Got message from " + session.getId() + "\n" + message);
                } catch (IOException ex) {
                }
            }
        });
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Peer " + session.getId() + " disconnected due to " + closeReason.getReasonPhrase());
    }

    @Override
    public void onError(Session session, Throwable error) {
        System.out.println("Error communicating with peer " + session.getId() + ". Detail: "+ error.getMessage());
    }
}

Let’s code the client endpoint as well (using the same set of APIs):

public class ProgrammaticEchoClient extends Endpoint {

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("Connected to server");
    }

    //a message handler and other life cycle implementations have been skipped on purpose...

}

Step #2 - Implement the ServerApplicationConfig Interface

It is part of the javax.websocket.server package and can be overridden to implement custom logic for endpoint deployment (for both annotated as well as programmatic endpoints)

public class CustomServerAppConfigProvider implements ServerApplicationConfig {

    @Override
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
        Set<ServerEndpointConfig> result = new HashSet<>();
        for (Class epClass : endpointClasses) {
            //need to ignore Client endpoint class
            if (epClass.equals(ProgrammaticChatEndpoint.class)) {
                ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(epClass, "/letschat").build();
                result.add(sec);
            }
        }
        return result;
    }

    @Override
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
        return Collections.emptySet();
    }
}

What About the Client Endpoint?

If required, you can create a your own instance of ClientEndpointConfig and use it while initiating a connection to the websocket server endpoint:

WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
ClientEndpointConfig config = ClientEndpointConfig.Builder.create().decoders(StockTickDecoder.class).build();
Session session = webSocketContainer.connectToServer(StockTickerClient().class, config, 
                                                    new URI("ws://hotstocks.com/ticker"));

Notes

  • Both the client as well as server endpoint config objects are nothing but object (programmatic) equivalents of the elements (value, encoders, decoders, configurator etc.) of the @ServerEndpoint and @ClientEndpoint annotations
  • Separate builder classes (ServerEndpointConfig.Builder and ClientEndpointConfig.Builder) were used to create server and client configuration instances respectively
  • The creation of a ServerEndpointConfig instance is mandatory since server endpoints cannot be deployed without a URI. This is not the case with client endpoints though – all they do is connect to an existing server endpoint.
  • The endpoint config (server & client) have the notion of a configurator which can be created and set via the respective builder methods.

Stay tuned for some more Websocket related action in the near future.

WebSocket Java EE Java (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • A Systematic Approach for Java Software Upgrades
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: