Chat API exposed over Web Socket

Last Updated on 07/02/2022 by Patryk Bandurski

On one of the Calicut MuleSoft Meetups, I was presenting the idea of Web Sockets on the MuleSoft platform. To make it more interactive, I prepared a demo application. It was a simple Chat API with a straightforward HTML page to post a message and see chat room messages. Today I want to describe this chat application on a step-by-step basis. This way, you can get hands-on experience publishing and consuming Web Sockets. Not sure what WebSockets are? Read my last article about it.

Let’s get started!

Scenario

The use case is plain and simple. This is a chat application. Chat guests once on the web page see a simple text form. This application establishes a connection with the web socket exposed by our Chat API. All incoming chat messages are immediately broadcasted to each active connection over the web socket.

Chat API exposing web socket to guests
Chat API exposing web socket to guests

Configuring Web Sockets

Global configuration

Web sockets are exposed over HTTP protocol. As a result, we need first define HTTP Listner configuration in global configuration. Sufficient is the basic configuration, just protocol, host, and port, like on the code below.

<http:listener-config name="HTTP_Listener_config" 
		doc:name="HTTP Listener config" >
		<http:listener-connection host="0.0.0.0" port="${http.private.port}" />
</http:listener-config>

Once done, we can configure WebSocket configuration on top of it. We need to specify that we configure connection and server settings (we expose endpoint). Like with regular services, I add a base path. Usually, I pick /ws to depict that we are playing with web sockets. Easy so far, isn’t it? Let’s see how the configuration looks in XML:

<websocket:config 
	name="WebSockets_Config" 
	doc:name="WebSockets Config">
	<websocket:connection>
		<websocket:server-settings 
			listenerBasePath="/ws" 
			listenerConfig="HTTP_Listener_config"/>
	</websocket:connection>
</websocket:config>

Exposing web socket

The global configuration is ready. We need to add a listener. We want to receive new chat messages. As a result, I pick the On New Inbound Message operation. I associate it with my web socket configuration and set a path. In my case, I set /messages. One extra tip, I set MIME Type to application/json to read json content in the flow.

Now our endpoint is available under ws://0.0.0.0:8091/ws/messages.

Broadcasting messages

Chat wouldn’t work without sending my message to all participants in the room. To achieve that, I will use broadcast operation on Web Sockets. In our case, the configuration is simple. We set the content and specify the path where we broadcast messages. What path should you pick? The same as on listener to send message to all active participants. One remark, unlike with listener the path must include base path, it isn’t added by default. Here it is how it looks like:

<websocket:broadcast 
  doc:name="Broadcast" 
  config-ref="WebSockets_Config" 
  path="/ws/messages"/>

Connecting to Web Socket

Our Chat API exposes now Web Socket on /ws/messages path. We can give that URI to consumers to start using our endpoint. In the attached example, I use JavaScript to connect to a web socket and listen to incoming messages. As this is not a blog about JavaScript, I paste a little bit of code with a brief overview. It may be helpful for you in case of testing it locally :).

//connect to WebSocket
var ws = new WebSocket("ws://localhost:8091/ws/messages");
			
//wait for messages back
ws.onmessage = function (event) {
	Console.log(JSON.parse(event.data));
}
			
// send message
function sendMessage() {
	var request = {
		name: name,
		message: msg
		};
	ws.send(JSON.stringify(request));
}

In the second line, we initiate the connection. Next, in the fourth line, we are hooked to onmessage event. In the event object, we will receive an entire message. In the example, I parse it to JSON and log it to the console. Then, to send the message, I prepared the sendMessage function. It takes a simple JSON object and sends it to a web socket.

What’s next

The source code you can find on my GitHub repository here. You can explore the source code and play with it. If you would like to sharpen your skills, try to:

  • enable rooms feature by introducing seperate groups on Web Socket
  • enable direct one-to-one communication

Have you made something like this? Show it off and share it. I can’t wait to see it.

How to run

You can build and run the API. Remember to add http.private.port=8091 to run configuration. Once the application is started. You can visit the http://localhost:8091/meetup page to show a simple Chat Room.

Web page consuming our Web Socket
Web page consuming our Web Socket

Summary

In just a few steps, I presented you with exposing Web Socket on chat API example. Who would think that a simple chat application can be just a short flow? As I wrote in what’s next, play with it by extending the features that real-life chat has, like rooms and direct messages.

I hope you enjoyed it. Cheers

Chat API exposed over Web Socket

Leave a Reply

Your email address will not be published.

Scroll to top