Registering with a URL for asynchronous notifications?

I am trying to understand more about asynchronous notifications. I have a url in the form:

http://www.sample.com/AsyncNotify?sessionId=xxxxxx

Now, if I call this URL with sessionId, this is equivalent to registering for asynchronous notifications. I use Apache HTTP Commons to do Http Post and Get. If so, how can I receive events from the server side? Should I forget this approach and use sockets instead? This is currently my approach:

HttpClient httpClient = new HttpClient;
String url = "http://www.sample.com/AsyncNotify?sessionId=xxxxxx"
GetMethod get = new GetMethod(url);
try {
   httpClient.executeMethod(get);
   //read the response
} catch(Exception e) {

}

What I was thinking of making a socket level connection inside a while loop and calling the handler whenever it receives some data, but is there a better way to achieve this?

EDIT:

I used xSocket to go to the next step, but the connection closes after 30 seconds:

         try {
            String _GETRequest = "/sample/notify";
            HttpClientConnection con = new HttpClientConnection("10.0.0.23", 5050);

            con.setConnectionTimeoutMillis(100000);
            GetRequest request = new GetRequest(_GETRequest);
            request.setParameter("id", id);

            IHttpResponseHandler responseHandler = new AsyncHandler();

            con.send(request, responseHandler);
            org.xlightweb.client.HttpClient httpClient = new org.xlightweb.client.HttpClient();
            request.setParameter("id", id);
            con.send(request, responseHandler);

                    // Don't let the program terminate. In other words,
                    // wait for a message from the server
            while(con.isOpen()) {};

            if(!con.isOpen()) {
            }

        } catch (ConnectException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
+3

Source: https://habr.com/ru/post/1751666/


All Articles