WebSocket API is another addition to the java.httpclient package in Java 9. As explained earlier, it enables having full duplex communication between the client and the server. This package provides various methods to help build messages, listen for events and messages, and handle partial messages. This is one of the important additions to the Java network API as it can process client’s requests seamlessly.

Here is a simple example to create a WebSocket endpoint and communicate it from a client.


We aleardy have a server side endpoint which listens to the incoming message and sends reply to the message. Application structure looks like.

WebSocket EndPoint Project Structure
WebSocket EndPoint Project Structure
WebSocket EndPoint

@ServerEndpoint annotation is used at type level and defines the current class as a websocket server endpoint. The value used in this annotation represents the URL where the endpoint will be listening for client connections.


WebSocket Client

As we already know that Java 9 is modularise so without making entry in module descriptor file we can not use internal modules. New WebSocket Client API is a part of HTTP module, Hence we will create requires in module-info.java

Module Descriptor

Let’s create WebSocket Listener, Which is responsible to listen and displays the message.

Let’s create Test Class to test endpoint [ws://localhost:8080/JavaWebsocket/websocket] with above listener.


Hello, codeNuclear

As we can see, Output message is a message replied from WebSocket endpoint.

That’s all for the WebSocket Client API in Java 9, Hope you like it, Keep Learning and Sharing! :)

Leave a Reply

Your email address will not be published. Required fields are marked *