Want a long poll using Soothing Knitwear API 2
My requirement:
I want to make an API like dropbox's
/longpoll_delta
i used jerser 2
in java for mine restful
. Actually I want to notify all clients when changes are detected on the server. So the server can take 2 hours or more and then notify all of its clients that I have an update. I don't want to use comet
, websocket
etc. For security.
1> Suggest how can I make such an API?
My shine: I created an async server API
Server code:
@GET
@Path("/longpoll")
@ManagedAsync
public void async(@Suspended final AsyncResponse asyncResponse)
{
new Thread(new Runnable()
{
@Override
public void run()
{
String result = veryExpensiveOperation();
asyncResponse.resume(result);
}
private String veryExpensiveOperation()
{
try
{
// put some long running code here
Thread.sleep(60000);
return "Hello World";
}
catch (Exception e)
{
e.printStackTrace();
return "error";
}
}
}).start();
}
So now for testing I created a client
Client code:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
public class JersyClient
{
public static void main(String args[]) throws InterruptedException, ExecutionException
{
ClientConfig clientConfig = new ClientConfig();
Client client = ClientBuilder.newClient(clientConfig);
WebTarget target = client.target("http://localhost:8080");
Invocation.Builder invocationBuilder = target.path("MyApp_3_3_5/api/1/longpoll").request();
invocationBuilder.header("Authorization", "Bearer yBOrnV6zlOrgoYxrMsfQ_BYZ5p37gALB");
final Future<Response> future = invocationBuilder.async().get(new InvocationCallback<Response>()
{
@Override
public void completed(Response response)
{
System.out.println("Response status code "
+ response.getStatus() + " received.");
System.out.println("In response " + response.readEntity(String.class));
}
@Override
public void failed(Throwable throwable)
{
System.out.println("Invocation failed.");
throwable.printStackTrace();
}
});
Response response = future.get();
System.out.println("your response " + response.readEntity(String.class));
// get() waits for the response to be ready
System.out.println("Go ahead");
}
}
But it doesn't work right.
OutPut:
Response status code 200 received.
In response
your response
Go ahead
This way the client doesn't wait for the actual response to send the server after 1 minute.
- Does the server have a problem code?
- Why isn't the client waiting for an answer?
- Should I achieve long_pooling using this way?
- if the server sends a response after 2 hours, then does it work in this case?
source to share
No one has answered this question yet
Check out similar questions: