JSON-RPC over WebSockets? Why not?

Posted by Sourced Blog on April 17, 2018
1669 words, 9 minute read

A lot of people have a personal pet project that has a simple domain and which allows them do play around with new technologies and try out some new (and sometimes crazy ideas). In my case, I have a REST API designed for POS systems for restaurants, as I have some experience with building software like this, and I know the domain quite well.

Since one of my previous projects involved JSON-RPC, I thought to myself, how can I make this a bit more sexy and challenging? Well, what I came up with was building a JSON-RPC system using an asynchronous communication like WebSockets. Aside from the fact that this may be totally useless to most people, I was up for the challenge to try and build a system.

In hindsight, it wasn’t really that big of a challenge. There are quite a few libraries out there that do the heavy lifting and in the end, it took me about a couple of hours to get something working. I used jsonrpc4j for the JSON-RPC part and Spring Boot to handle WebSocket interaction.

So first I started by enabling WebSocket support in my Spring Boot app:

If a web socket is opened on http://localhost:8080/websocket/json-rpc-request/product and you send a valid JSON-RPC payload, the correct method will be called on the service and the message will be sent to a user reply channel. The reason for this is by specifying this, only the user that has sent the request will receive the reply.

And that’s it. But how would you use this in practice?

Well, first I needed to build some kind of client that was able to call these kinds of services. What I came up with was this, which is a kind of skeleton for generic JSON-RPC Websocket cients.

Mind you, this is all a very naive implementation of the functionality needed to make this work. There are quite a few corner cases that haven’t been covered (error handling, security, concurrent usage), but I hope you see the possibilities in combining 2 technologies to create interesting synergies.