Simple implementation of long polling based on HTTP

Keywords: Javascript less JSON Web Server

The common communication mode between Web client and server based on Ajax (http) is divided into short connection and long polling.

Short connection: every time the client and the server perform HTTP operation, they establish a connection, and the connection will be interrupted when the task ends.

In the long polling mechanism, the client requests data from the server like traditional polling. However, if the server has no data that can be returned to the client immediately, it will not return an empty result immediately,

Instead, keep the request waiting for the data to arrive (or the appropriate timeout: less than the ajax timeout), and then return the data to the client as a result.

The long polling mechanism is shown in the following figure:

The web client code is as follows:

//Polling messages to the rear head
    function longPolling(){
        $.ajax({
            async : true,//asynchronous
            url : 'longPollingAction!getMessages.action', 
            type : 'post',
            dataType : 'json',
            data :{},
            timeout : 30000,//Timeout setting 30 seconds
            error : function(xhr, textStatus, thrownError) {
                longPolling();//Request again after an unexpected error
            },
            success : function(response) {
                message = response.data.message;
                if(message!="timeout"){
                    broadcast();//Post message after receiving message
                }
                longPolling();
            }
        });
    }

The web server code is as follows:

public class LongPollingAction extends BaseAction {
    private static final long serialVersionUID = 1L;
    private LongPollingService longPollingService;
    private static final long TIMEOUT = 20000;// Timeout set to 20 seconds

    public String getMessages() {
        long requestTime = System.currentTimeMillis();
        result.clear();
        try {
            String msg = null;

            while ((System.currentTimeMillis() - requestTime) < TIMEOUT) {
                msg = longPollingService.getMessages();
                if (msg != null) {
                    break; // Jump out of loop and return data
                } else {
                    Thread.sleep(1000);// Dormancy for one second
                }
            }
            if (msg == null) {
                result.addData("message", "timeout");// overtime
            } else {
                result.addData("message", msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }
    
    public LongPollingService getLongPollingService() {
        return longPollingService;
    }

    public void setLongPollingService(LongPollingService longPollingService) {
        this.longPollingService = longPollingService;
    }

}

Posted by rubenc on Mon, 30 Dec 2019 21:47:05 -0800