Home > Web Front-end > JS Tutorial > Summary of some web communication knowledge points in JavaScript (share)

Summary of some web communication knowledge points in JavaScript (share)

青灯夜游
Release: 2021-02-24 10:01:31
forward
2353 people have browsed it

Summary of some web communication knowledge points in JavaScript (share)

Web communication is a very big topic and covers a wide range of areas. Because I have recently learned some web communication knowledge in javascript, I will summarize it here.

1. Foreword

1. Comet technology

As the front-end of Web applications, the browser has limited processing functions. The development of browsers requires client software upgrades. At the same time, the diversity of client browser software also affects the promotion of new browser technologies in a sense.

In Web applications, the main job of the browser is to send requests, parse the information returned by the server, and display it in different styles. AJAX is the result of the development of browser technology. It improves the responsiveness of single-user operations by sending asynchronous requests on the browser side.

But the Web is essentially a multi-user system. For any user, the server can be considered as another user. The development of existing AJAX technology cannot solve the problem of transmitting updated information to the client in real time in a multi-user Web application, so users may operate under "outdated" information. The application of AJAX makes it possible to update background data more frequently.

With the development of the Internet, web applications emerge in endlessly, including various website monitoring, instant quotation, and instant messaging systems. In order to provide users with a better experience, the server needs to frequently push information to the client.

Developers generally use AJAX-based long polling or stream processing based on iframe and htmlfile. Of course, some programs require various plug-ins (Java applet or Flash) to be installed on the client to support "push" information with relatively good performance.

2. Long and short connections in HTTP protocol

The operation steps of short connection are: establish connection-data transmission-close connection...Establish connection-data transmission- Close the connection

The steps for long connection are: establish connection-data transmission...(keep the connection)...data transmission-close connection

The difference between long connection and short connection The main difference lies in the different shutdown strategies adopted by the client and server. A short connection only performs one data transmission before closing the connection after establishing the connection, while a long connection performs multiple data transmissions until the connection is closed (the connection is closed through the Connection: closed header field in a long connection).

2. Web communication

First of all, we must understand the various states of readystate of xhr.

Summary of some web communication knowledge points in JavaScript (share)

1. Polling

Polling is a working mode that "pulls" information. Set a timer to periodically ask the server whether there is information. After each connection is established to transmit data, the link will be closed.

Front-end implementation:

var polling = function(url, type, data){
    var xhr = new XMLHttpRequest(), 
        type = type || "GET",
        data = data || null;

    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4) {
            receive(xhr.responseText);
            xhr.onreadystatechange = null;
        }
    };

    xhr.open(type, url, true);
    //IE的ActiveXObject("Microsoft.XMLHTTP")支持GET方法发送数据,
    //其它浏览器不支持,已测试验证
    xhr.send(type == "GET" ? null : data);
};

var timer = setInterval(function(){
    polling();
}, 1000);
Copy after login

During the polling process, if the previous xhr object has not been transmitted due to network reasons, the timer has started the next query, and the last Whether the transmission will still be in the queue, I have not studied this issue. If you are interested, you can write an ajax request management queue yourself.

2. Long-polling

In fact, there is nothing special about long polling. It is to connect the xhr object immediately when it closes the connection~ Read the code :

var longPoll = function(type, url){
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function(){
        // 状态为 4,数据传输完毕,重新连接
        if(xhr.readyState == 4) {
            receive(xhr.responseText);
            xhr.onreadystatechange = null;

            longPoll(type, url);
        }
    };

    xhr.open(type, url, true);
    xhr.send();
}
Copy after login

As long as the server disconnects, the client will connect immediately without letting him have a moment of rest. This is long polling.

3. Data flow

The data flow method accepts data before the established connection is disconnected, that is, when the readystate is 3, but the troublesome thing is also here, because the data is being For transmission, the xhr.response you get may be half the data. It is best to define a data transmission protocol. For example, the first 2 bytes represent the length of the string, and then you only obtain the content of this length, and then change the position of the cursor.

If the data format is: data splitChar data is the data content, splitChar is the data end mark (length is 1). Then the transmitted data content is data splitChar data splitChar data splitChar...

var dataStream = function(type, url){
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function(){

        // 状态为 3,数据接收中
        if(xhr.readyState == 3) {
            var i, l, s;

            s = xhr.response; //读取数据
            l = s.length;     //获取数据长度

            //从游标位置开始获取数据,并用分割数据
            s = s.slice(p, l - 1).split(splitChar);

            //循环并操作数据
            for(i in s) if(s[i])  deal(s[i]);

            p = l;  //更新游标位置

        }

        // 状态为 4,数据传输完毕,重新连接
        if(xhr.readyState == 4) {
            xhr.onreadystatechange = null;

            dataStream(type, url);
        }
    };

    xhr.open(type, url, true);
    xhr.send();
};
Copy after login

There is a problem with this code. When readystate is 3, the data can be obtained, but the data obtained at this time may only be the whole Part of the data, the second half cannot be obtained.

readystate will not change before the data transmission is completed, which means that it will not continue to accept the remaining data. We can monitor readystate regularly, as you can see in the example below.

This kind of processing is not complicated, but there are problems. The above polling and long polling are supported by all browsers, so I did not write IE-compatible code, but here, the lower version of IE does not allow reading data when readystate is 3, so we must use other methods way to achieve it.

Before ajax entered the web topic, we already had a magic weapon, that is, iframe. Using iframe, we can still obtain data asynchronously. For lower versions of IE, we can use iframe to accept data streams.

if(isIE){
    var dataStream = function(url){
        var ifr = document.createElement("iframe"), doc, timer;

        ifr.src = url;
        document.body.appendChild(ifr);

        doc = ifr.contentWindow.document;

        timer = setInterval(function(){

            if(ifr.readyState == "interactive"){
                // 处理数据,同上
            }

            // 重新建立链接
            if(ifr.readyState == "complete"){
                clearInterval(timer);

                dataStream(url);
            }
        }, 16);
    };
};
Copy after login

定时去监听iframe的readystate的变化,从而获取数据流,不过,上面的处理方式还是存在问题。数据流实现“服务器推”数据的原理是什么呢,就是文档(数据)还没有加载完,这个时候浏览器的工作就是去服务器拿数据完成文档(数据)加载。

所以上述利用iframe的方式获取数据,会使浏览器一直处于加载状态,title上的那个圈圈一直在转动,鼠标的状态也是loading,这看着是相当不爽的。

幸好,IE提供了HTMLFile对象,这个对象就相当于一个内存中的Document对象,它会解析文档。所以我们创建一个HTMLFile对象,在里面放置一个IFRAME来连接服务器。这样,各种浏览器就都支持了。

if(isIE){
    var dataStream = function(url){
        var doc = new ActiveXObject("HTMLFile"), 
            ifr = doc.createElement("iframe"), 
            timer, d;

        doc.write("
Copy after login
");         ifr.src = url;         doc.body.appendChild(ifr);         d = ifr.contentWindow.document;         timer = setInterval(function(){             if(d.readyState == "interactive"){                 // 处理数据,同上             }             // 重新建立链接             if(d.readyState == "complete"){                 clearInterval(timer);                 dataStream(url);             }         }, 16);     }; };

4.websocket

websocket是前端一个神器,ajax用了这么久了,相关技术也是很成熟,不过要实现个数据的拉取确实十分不易,从上面的代码中也看到了,各种兼容性问题,各种细节处理问题。

var ws = new WebSocket("ws://www.example.com:8888");

ws.onopen = function(evt){};
ws.onmessage = function(evt){
    deal(evt.data);
};
ws.onclose  = function(evt){};

//ws.close();
Copy after login

新建一个WebSocket实例,一切就OK了,ws:// 是websocket的连接协议,8888为端口号码。onmessage中提供了data这个属性,相当方便

5.EventSource

HTML5中提供的EventSource这玩意儿,这是无比简洁的服务器推送信息的接受函数。

new EventSource("test.php").onmessage=function(evt){
    console.log(evt.data);
};
Copy after login

简洁程度和websocket是一样的啦,只是这里有一个需要注意的地方,test.php输出的数据流应该是特殊的MIME类型,要求是"text/event-stream",如果不设置的话,你试试~ (直接抛出异常)

6.ActionScript

情非得已就别考虑这第六种方式了,虽说兼容性最好,要是不懂as,出了点bug你也不会调试。

具体实现方法:在 HTML 页面中内嵌入一个使用了 XMLSocket 类的 Flash 程序。JavaScript 通过调用此 Flash 程序提供的套接口接口与服务器端的套接口进行通信。JavaScript 在收到服务器端以 XML 格式传送的信息后可以很容易地控制 HTML 页面的内容显示。

7.Java Applet套接口

三、后端处理方式

本文主要是总结Javascript的各种通讯方式,后端配合node来处理,应该是挺给力的。

var conns = new Array();

var ws = require("websocket-server");
var server = ws.createServer();

server.addListener("connection", function(connection){
  console.log("Connection request on Websocket-Server");
  conns.push(connection);
  connection.addListener('message',function(msg){
        console.log(msg);
        for(var i=0; i<conns.length server.listen><p>下面是一个php的测试demo。</p>
<pre class="brush:php;toolbar:false">header('Content-Type:text/html; charset=utf-8');
while(1){
    echo date('Y-m-d H:i:s');
    flush();
    sleep(1);
};
Copy after login

四、web 通信方式利弊分析

轮询,这种方式应该是最没技术含量的,操作起来最方便,不过是及时性不强,把定时器的间隔时间设置的短一些可以稍微得到缓和。

长轮询,算是比较不错的一个web通讯方式,不过每次断开连接,比较耗服务器资源,客户端到无所谓。

数据流,他和长轮询不同之处是接受数据的时间不一样,数据流是readystate为3的时候接受,低版本IE不太兼容,处理起来略麻烦,而且还要自己设计数据传输协议。不过他对资源的消耗比上面几种都可观。

websocket和EventSource,两个利器,不过,没几个浏览器支持,这是比较让人伤心~

ActionScript和Java Applet,两者都是需要在客户端安装插件的,一个是Flash插件,一个是Java插件,而且搞前端的人一般对这东西不太熟悉,如果没有封装比较好的库可以使用,那建议还是别用了。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Summary of some web communication knowledge points in JavaScript (share). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template