Search code examples
htmlspring-bootstreamingspring-websocketjava-websocket

Streaming data for a realtime web application


I am building a web application where i need to push continuous data from server to client for a specific interval with one time request from client. Its the Same as in trading application where user's login the application once and post that he is able to see the rates changing continuously without making any further requests.

While researching i found out, by polling we can achieve this but at the same time it is also an overhead on the number of connections.

My server is a micro-service model and client is HTML5.

Suggestions and help will be appreciated.


Solution

  • You can use Server Sent Events. It works exactly as you need it. The client connects one time and then the server send an event (i.e. an object serialized to JSON) every time something changes in the backend by registering a callback function to be called every time an event is received.

    Below is a sample data flow:

    event: userconnect
    data: {"username": "bobby", "time": "02:33:48"}
    
    event: usermessage
    data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
    
    event: userdisconnect
    data: {"username": "bobby", "time": "02:34:23"}
    
    event: usermessage
    data: {"username": "sean", "time": "02:34:36", "text": "Bye, bobby."}
    

    Here is a tutorial for Spring.