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

  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Building a Dynamic Chat Application: Setting up ChatGPT in FastAPI and Displaying Conversations in ReactJS
  • Create a Multi-tenancy Application In Nest.js - Part 3

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  1. DZone
  2. Coding
  3. Tools
  4. Publish WebSocket in the Experience Layer

Publish WebSocket in the Experience Layer

The main focus of the article is to show you how to publish a web socket for your consumers, in it I will describe what web socket gives us.

By 
Patryk Bandurski user avatar
Patryk Bandurski
·
Updated Jan. 22, 21 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
10.9K Views

Join the DZone community and get the full member experience.

Join For Free

Some time ago, MuleSoft introduced WebSocket Connector. In this article, I briefly describe what WebSocket gives us in the context of integration. The main focus of the article is to show you how to publish a WebSocket for your consumers. 

WebSocket

So, the first question is, what is a WebSocket? WebSocket is a communication protocol over TCP that enables bidirectional communication between client and server.

web socket and HTTP

WebSocket vs. HTTP communication

As you can see in the diagram above, the client initiates a connection over WebSocket or secure WebSocket (wss), and then the server can send back messages to the client. Unlike with HTTP protocols, we do not need to do any pulling. Once the connection is established, the server can send as many requests as it likes.

The greatest benefit of using WebSocket instead of HTTP is performance, as we do not need to establish a new connection. What is more, we do not need to introduce any sort of pulling mechanism.

WebSocket Connector

Exchange Rates Case

We want to consume forex exchange rates and display them on our banking portal. As they are changing rapidly, we would like to keep values up-to-date. I have decided to expose a WebSocket endpoint to stream changes that occur on the client.

exchange rates

MuleSoft case with published WebSocket endpoint

MuleSoft best practice is API-led connectivity. As a result, in our case, we have three layers. We have the Banking Portal Experience API (XAPI), the Banking Process API (PAPI), and the Banking Forex System API (SAPI). In order to make the data flow smoothly, we will use Amazon SQS queues to exchange data between layers – as in the diagram above.

Our system API reads exchange rates and publishes them to the exchange-rates-sapi queue. The Banking Process API reads values from this queue and saves them to the exchange-rates-papi queue. This queue will be read by the application in the Experience layer. The Banking Portal XAPI broadcasts exchange rates to open WebSockets.

When the client initiates a WebSocket connection, it must decide on the primary currency. In other words, if exchange rates should be calculated against USD, EUR, PLN, etc.

WebSockets Configuration

WebSockets configuration requires HTTP Listener configs. In the picture below, you can see that we have to assign an existing HTTP_Listener_config to a WebSocket configuration via the Listener config property.

http_listener

WebSocket global configuration

You can specify how long the connection should be kept alive while idle. In my scenario, I have decided to kill the connection after 60 minutes.

WebSocket Connector Operations

In order to expose WebSocket connections we have two listeners.

On New Inbound Connection is triggered when the client initiates the connection. Below you can see a sample line of JavaScript that performs this action. In this case, you don’t have any payload, but you receive the headers/metadata.

JavaScript
 




x


 
1
var ws = new WebSocket("ws://localhost:8081/ws/exchange-rates");


On New Inbound Message is triggered when the client sends the message on an already established WebSocket connection. The client can send a body that Mule saves within the payload – like JSON. In this part, we often subscribe to some events like chat entries entered by all the users or exchange rate changes. We can also send a message back to the client if we like.

In the JavaScript snippet below, you can find the code for sending a message to WebSocket.

JavaScript
 




xxxxxxxxxx
1


 
1
var request = {
2
  base: "PLN"
3
};
4
ws.send(JSON.stringify(request)); 


In both cases, you need to provide the path on which the application listens. My demo application uses the following path to connect to WebSocket: ws://localhost:8081/ws/exchange-rates.

Sending Messages With WebSocket

MuleSoft gives us two convenient operations: Send and Broadcast.

Send is used to send one message to a concrete client. We need to specify the socket identifier. We receive this id in Mule attributes (attributes.socketId) while the connection is initiated. When we want to send the same message to more consumers, we can use broadcast.

In the Broadcast operation, we should specify the body, the path on which we want to look for active WebSocket connections, and the socket type. The last attribute should be set to INBOUND. This value indicates that the only connection to our published socket is considered. Last, but not least, we could specify groups. The developer specifies the group.

So let’s see them in action.

Send Operation

successful subscription

Send operation configuration in Anypoint Studio

In the above screenshot, you can see that I am sending a message to a recipient identified by the socketId. I also specify the JSON body that can assure the client that the connection has been successfully established.

The socketId is available in the attributes in flows with the WebSocket listeners. If you would like to access them in other parts of your application you should save them, for example in the ObjectStore.

Subscription and Broadcasting

We can broadcast the message to all active clients. However, we may be interested in restricting specific groups. In order to achieve this, we need to use the subscribe-groups operation.

XML
 




xxxxxxxxxx
1


 
1
<websocket:subscribe-groups
2
  doc:name="Rates groups"
3
  config-ref="WebSockets_Config"
4
  socketId="#[attributes.socketId]">
5
    <websocket:groups >
6
      <websocket:group value='#[payload.base ++ "_rates"]' />
7
    </websocket:groups>
8
</websocket:subscribe-groups>


As you can see, we need to provide the socketId in order to identify the client and one or more groups. In my case, I have decided to name the group dynamically. As a result, I will have three groups with names like USD_rates, PLN_rates, and EUR_rates.

Now when someone subscribes just for USD_rates, they won’t receive updates on PLN and EUR.

Broadcasting a message is a trivial task. We just use a broadcast operation. In the code below, you can see that I have only selected the most important parts: the path and groups.

XML
 




xxxxxxxxxx
1


 
1
<websocket:broadcast
2
  doc:name="Broadcast"
3
  config-ref="WebSockets_Config"
4
  path="/ws/exchange-rates" socketType="INBOUND">
5
    <websocket:groups >
6
      <websocket:group value='#[vars.base ++ "_rates"]' /> 
7
    </websocket:groups>
8
</websocket:broadcast>


Source Code

Source code is available at GitHub. The code has been prepared using the Mule 4.2.2 EE runtime and WebSocket version 1.0.0.

  • Application in experience layer – with the JavaScript to test the connection.
  • Process layer application.
  • Application in the system layer – connecting to a real forex API.

Summary

I like the idea of web sockets as they introduce the bidirectional traffic without any additional overhead like using HTTP(S). MuleSoft connectors are ready and easy to use. Maybe you had a case when that could be useful to use, but was not yet available in Mulesoft. In my case, I can imagine a couple of usage scenarios.

Cheers!

WebSocket Connection (dance) application

Published at DZone with permission of Patryk Bandurski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Building a Dynamic Chat Application: Setting up ChatGPT in FastAPI and Displaying Conversations in ReactJS
  • Create a Multi-tenancy Application In Nest.js - Part 3

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!