Member-only story
Implementing a Websocket Server using Ballerina

In a previous post I discussed about Websocket, its use and how applicable it’s today while comparing it with HTTP/2. In the same post I also showed a sample prototype chat application that utilize Websockets. The front end uses JavaScript and the server is implemented using Python.
In this post I’m going to use the same front-end application but the Websocket server is going to be implemented using Ballerina which is a general purpose programming language that makes integration programming easy. I wrote about why you should try out Ballerina if you are new to the language here.
Implementing the Websocket service in Ballerina
Ballerina support building network services natively. It doesn’t require any third party library for such service implementations. Let’s look at how can we implement a websocket service in Ballerina.
The websocket service code can be found below. Let’s try to understand what happens in this code.
Websocket service listener is defined in lines 8–12. It spefies the port and returns a service class instance named ‘ChatService’. The ‘ChatService’ is then defined as a service class in lines 14–77 (ballerina’s one way of abstracting various network services such as websocket, graphql etc.) These lines contain the bulk of the websocket service implementation.
When websocket listener module is initialized ‘init’ method will be called. Then when the connection is established ‘onOpen’ method will be called. Similarly when the connection is closed ‘onClose’ will be called. When the client sends a message ‘onMessage’ will be called. There are other variants of ‘onMessage’ as well. You can find the full list of methods on that these service class support here.
When a connection comes in, within ‘onOpen’, ‘lastUserId’ is incremented and ‘userMap’ is populated with caller’s connection Id and ‘lastUserId’. Similarly ‘connectionMap’ is populated with caller’s connection Id and caller instance…