Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Server to client communication

I'm developing a Java API for an Adndroid app in Spring. Right now my API is 100% REST and stateless. For the client to receive data, it must send a request first.

However, what I need is the server to send data to the to the client /not the client to the server fisrt/ whenever it is ready with it's task.

I think that some kind of session must be created between the two parties.

My question is: How can I achieve this functionality of the SERVER sending data to the CLIENT when it's ready with it's task? /It is unknown how long the task will take./

What kind of API should I develop for this purpose?

One idiotic workaround is sending a request to the server every n seconds but I'm seeking for a more intelligent approach.

like image 320
BabbevDan Avatar asked Sep 24 '16 18:09

BabbevDan


1 Answers

There are multiple options available. You can choose what suits best for you.

  1. Http Long Polling - In this, server holds the request until it's ready with its task (in your case). Here, you don't have to make multiple requests every few seconds (Which is Http Polling).

  2. Server Sent Events - In this, server sends update to the client without long-polling. It is a standardized part of HTML 5 - https://www.w3.org/TR/eventsource/

  3. Websockets - Well, websockets work in duplex mode and in this a persistent TCP connection is established. Once TCP connection is established, both server and client sends data to and fro. Supported by most modern browsers. You can check for Android Websocket Library like autobahn and Java websocket.

  4. SockJs - I would recommend to go with this option instead of plain WebSocket. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#websocket-fallback-sockjs-enable

like image 177
Mansoor Avatar answered Oct 27 '22 19:10

Mansoor