简体   繁体   English

基于香草JS AJAX长轮询的WebSocket最简单方法

[英]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). 我用香草JavaScript准备了AJAX长轮询(实时)的最简单方法,没有像jQuery这样的任何库...代码基于PHP文件server.php (仅此)读取的data.txt timestamp而工作。

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). 现在,我想知道如何在websocket准备类似的示例(没有任何库,只需清理JS / PHP)。

It is possible? 有可能的?

Websocket is a different protocol than HTTP (it uses the HTTP upgrade mechanism). Websocket是与HTTP不同的协议(它使用HTTP升级机制)。 So you'll have to adapt your webserver AND any reverse proxy etc. to handle websocket connections. 因此,您必须调整您的Web服务器和任何反向代理等以处理WebSocket连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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