简体   繁体   中英

The simplest way of websocket based on vanilla JS AJAX long polling

I prepare the simplest way of AJAX long polling (realtime) in vanilla JavaScript, without any libraries like jQuery... The code works based on timestamp of data.txt read by PHP file server.php (that's all).

function realtime(timestamp) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', 'server.php' + (typeof timestamp !== 'undefined' ? '?timestamp=' + timestamp : ''), true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var result = JSON.parse(xhr.responseText);

            document.getElementById('response').innerHTML = result.content;

            realtime(result.timestamp);
        }
    };
    xhr.send();
}

realtime();

Now, I would like to know how to prepare similar example in websocket (without any libraries, just clean JS/PHP).

It is possible?

Websocket is a different protocol than HTTP (it uses the HTTP upgrade mechanism). So you'll have to adapt your webserver AND any reverse proxy etc. to handle websocket connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM