Recently, I was trying some complex distributed pattern in server development.
In one scenario, client calls the web service, and web service parse request then pass it to a background worker via DynamoDB or message queue. The worker will send result to the message bus, and the web socket server fetch this result to notify the browser.
However, some how this async design must have a sync implementation. Namely, instead of return empty response to the client then let client wait for the notification, the web service must return the result itself, which means the web service should play roles as a web socket client to fetch the result from web socket server.
Use of socket.io-java-client
To integrate with my Play! 2 (Java), I choose nkzawa/socket.io-client.java as socket client library, because its dependency can easily be managed in sbt, like:
After importing this library, you could create socket within your API. In my case, I have to create socket for each request due to web socket server implementation:
Note that in this library, Socket internally manages a cache to store established socket using a hash map with host of the url as its key.
Since I want to create socket for each request and every socket I will create definitely has the same host, so I will have to use forceNew option to make IO.socket return me a new socket every time.
Use socket to implement sync call
To make API wait for the result sent by web socket server, I must hold this socket until socket server send things back after connecting. So, let us make a new class for that:
Integrate with Play!
Play! framework has very good sense to deal with thread holding situation.
To avoid blocking the web service, we are going to use F.Promise<Result>, despite that every action in play is actually returning F.Promise<Result>.
Simple test web socket code
You can also build a simple socket server to check your code(node.js with socket.io):
Maybe you just need one or two parts above to solve your own problem, like use of socket client library or simple use of Promise in Play!. But it is my first post in Qiita, and I am really fond of some opinions and critics. For example, I don’t think create socket every time is very efficient, maybe I could build a helper to take charge of that.