<label id="tc74t"></label>
    \r\n    

    webSocket實(shí)例<\/h2>\r\n    \r\n    建立連接<\/button>\r\n    發(fā)送數(shù)據(jù)<\/button>\r\n    斷開(kāi)連接<\/button>\r\n    <\/p>\r\n    

    国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

    Table of Contents
    1. Basic knowledge of WebSocket communication
    2、HTML5 WebSockets API
    1.WebSocket通信基礎(chǔ)知識(shí)
    Home Web Front-end H5 Tutorial WebSocket communication in Html5

    WebSocket communication in Html5

    Feb 16, 2017 pm 02:29 PM

    1. Basic knowledge of WebSocket communication

    WebSocket is a network technology for full-duplex communication between browsers and servers that HTML5 began to provide. Using ws or wss protocol, it is the next generation client-server asynchronous communication method.

    In the WebSocket API, the browser and the server only need to perform a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

    Now, in order to achieve instant messaging (real-time), many websites use the technology Polling(polling). Polling is when the browser sends an HTTP request to the server at a specific time interval (such as every 1 second), and then the server returns the latest data to the client's browser. This traditional HTTP request d model brings obvious shortcomings – the browser needs to continuously send requests to the server. However, the header of the HTTP request is very long, and the data contained in it may only be a small value. , which will take up a lot of bandwidth.

    The latest technology to achieve the effect of polling is Comet - using AJAX. However, although this technology can achieve full-duplex communication, it still needs to issue a request (reuqest).

    WebSocket communication in Html5

    In the WebSocket API, the browser and the server only need to do a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two. In this WebSocket protocol, it brings us two major benefits to achieve instant service:

    1. Header

    #The Header that communicates with each other is very small - about only 2 Bytes

    2. Server Push

    The server can actively transmit data to the client. As long as the socket opened by the client establishes a connection with the server, the data can be pushed. Go to this socket and change from passive to active.

    WebSocket is not limited to Ajax (or XHR) communication, because Ajax technology requires the client to initiate a request, and the WebSocket server and client can push information to each other; domain communication.
    The smart thing about Ajax technology is that there is no designed way to use it. WebSocket is created for the specified target and used to push messages in both directions.

    2. HTML5 WebSockets API

    WebSocket object

    WebSocket is a sub-object of the window object in the DOM. It has:

    • WebSocket(url) constructor.

    • readyState. Read-only attribute, its value can be CONNECTING (0), OPEN (1), CLOSED (3).

    • boolean send(in DOMString data)

    • void close() two methods, used to send messages and close WebSocket connections respectively

    onopen, onmessage, and onclosee event attributes, respectively for the three WebSocket events of open, message, and close.

    1. Browser support detection

    Detection of browser support

    function loadDemo() {  
        if (window.WebSocket) {  
            //supported  
        } else {  
            // not supported  
        }  
    }

    2. Creation of WebSocket objects and server connection

    Requirements To connect to a communication endpoint, simply create a new WebSocket instance and provide the URL of the peer you wish to connect to. The ws:// and wss:// prefixes represent WebSocket connections and secure WebSocket connections respectively.

    url = "ws://localhost:8080/echo";  w = new WebSocket(url);

    When establishing a WebSocket connection, you can list the protocols that the web application can use. The second parameter of the WebSocket constructor can be either a string or a group of strings.

    w = new WebSocket(url, ["proto1", "proto2"]);

    Assume that proto1 and proto2 are well-defined, possibly registered, and standardized protocol names that can be understood by both the client and the server. The server selects the preferred protocol from the list.

    onopen = function(e) {  
        //確定服務(wù)器選擇的協(xié)議  
        log(e.target.protocol);  
    }

    3. Add event listener

    WebSocket programming follows the asynchronous programming model; after opening the socket, you only need to wait for the event to occur without actively polling the server, so you need to add the event listener to the WebSocket object. Add a callback function to listen for events.
    The WebSocket object has three events: open, close and messageThere are three corresponding event listeners onopen, onmessage and onclose to handle each stage of the connection life cycle. Of course, onerror can also be used to listen for errors. , as shown in the following example.

    w.onopen = function() {  
        log("open");  
        w.send("send message");  
    }  
    w.onmessage = function(e) {  
        log(e.data);  
    }  
    w.onclose = function(e) {  
        log("closed");  
    }  
    w.onerror = function(e) {  
        log("error");  
    }

    4. Send a message

    When the socket is open (that is, after onopen and before onclose), you can use the send method to send a message. After the message is sent, you can call the close method to terminate the connection, or you can not do this and keep it open.

    w.send();

    You may want to measure how much data is backed up in the send buffer before calling the Send() function. The bufferAmount property represents the number of bytes that have been sent on the WebSocket but not yet written to the network. It is useful for adjusting the sending rate.

    document.getElementById("sendButton").onclick = function() {  
        if (w.bufferedAmount < bufferThreshold) {  
            w.send(document.getElementById("inputMessage").value);  
        }  
    }

    WebSocket API supports sending Blob and ArrayBuffer instances in the form of binary data

    var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]);  
    w.send(a.buffer);

    Constant-readyState attribute

    These constants are the takers of the readyState attribute Value, which can be used to describe the status of the WebSocket connection.

    ConstantValueDescription
    CONNECTING0The connection has not been opened yet.
    OPEN1The connection is open and ready for communication.
    CLOSING2The connection is in the process of closing.
    CLOSED3The connection has been closed, or the connection cannot be established.

    3.實(shí)例

    <!DOCTYPE html><html><head>
        <title>webSocket實(shí)例</title></head><body>
        <h2>webSocket實(shí)例</h2>
        <input type="text" id="text">
        <button type="" id="connect" onclick="connect()">建立連接</button>
        <button type="" id="send" onclick="send()">發(fā)送數(shù)據(jù)</button>
        <button type="" id="disconnect" onclick="disconnect()">斷開(kāi)連接</button>
        <p id="message"></p>
        <script type="text/javascript">
            var socket;        var readyState = ["正在連接","已經(jīng)連接","正在斷開(kāi)","已經(jīng)斷開(kāi)"];        var message = document.getElementById(&#39;message&#39;);        function connect(){
    
                try{                var url = &#39;ws:localhost/test&#39;;
                    socket = new webSocket(url);
                    message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    socket.onopen = function(){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    }
                    socket.onmessage = function(msg){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+&#39;<br>&#39;+ "接收數(shù)據(jù)" + msg.data +"</p>";
                    }
                    socket.onclose = function(){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    }
                }catch(exception){                // socket.onerror  = function(){
                        message.innerHTML += "<p>發(fā)生錯(cuò)誤!"+"</p>";                // }
                }
            }        function send(){
                var text = document.getElementById(&#39;text&#39;).value;            try{
                    socket.send(text);
                    message.innerHTML += "<p>發(fā)送數(shù)據(jù):" + text +"</p>";
                }catch(exception){
                    message.innerHTML += "<p>發(fā)送數(shù)據(jù)出錯(cuò)</p>";
                }
            }        function disconnect(){
                socket.close();
            }    </script></body></html>

    1.WebSocket通信基礎(chǔ)知識(shí)

    WebSocket是HTML5開(kāi)始提供的一種瀏覽器與服務(wù)器間進(jìn)行全雙工通訊的網(wǎng)絡(luò)技術(shù)。 使用ws或wss協(xié)議,是下一代客戶端-服務(wù)器的異步通信方法。

    在WebSocket API中,瀏覽器和服務(wù)器只需要要做一個(gè)握手的動(dòng)作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。

    現(xiàn)在,很多網(wǎng)站為了實(shí)現(xiàn)即時(shí)通訊(real-time),所用的技術(shù)都是輪詢(polling)。輪詢是在特定的的時(shí)間間隔(time interval)(如每1秒),由瀏覽器對(duì)服務(wù)器發(fā)出HTTP request,然后由服務(wù)器返回最新的數(shù)據(jù)給客服端的瀏覽器。這種傳統(tǒng)的HTTP request d的模式帶來(lái)很明顯的缺點(diǎn) – 瀏覽器需要不斷的向服務(wù)器發(fā)出請(qǐng)求(request),然而HTTP request 的header是非常長(zhǎng)的,里面包含的數(shù)據(jù)可能只是一個(gè)很小的值,這樣會(huì)占用很多的帶寬。

    而最比較新的技術(shù)去做輪詢的效果是Comet – 用了AJAX。但這種技術(shù)雖然可達(dá)到全雙工通信,但依然需要發(fā)出請(qǐng)求(reuqest)。

    WebSocket communication in Html5

    在 WebSocket API,瀏覽器和服務(wù)器只需要要做一個(gè)握手的動(dòng)作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。在此WebSocket 協(xié)議中,為我們實(shí)現(xiàn)即使服務(wù)帶來(lái)了兩大好處:

    1. Header

    互相溝通的Header是很小的-大概只有 2 Bytes

    2. Server Push

    服務(wù)器可以主動(dòng)傳送數(shù)據(jù)給客戶端,只要客戶端打開(kāi)的socket與服務(wù)器建立連接后,就可以把數(shù)據(jù)推送到這個(gè)socket上,從被動(dòng)轉(zhuǎn)為主動(dòng)。

    WebSocket并不限于以Ajax(或XHR)方式通信,因?yàn)锳jax技術(shù)需要客戶端發(fā)起請(qǐng)求,而WebSocket服務(wù)器和客戶端可以彼此相互推送信息;XHR受到域的限制,而WebSocket允許跨域通信。
    Ajax技術(shù)很聰明的一點(diǎn)是沒(méi)有設(shè)計(jì)要使用的方式。WebSocket為指定目標(biāo)創(chuàng)建,用于雙向推送消息。

    2、HTML5 WebSockets API

    WebSocket對(duì)象

    WebSocket在DOM中是window對(duì)象的子對(duì)象,它具有:

    • WebSocket(url)構(gòu)造函數(shù)。

    • readyState。只讀屬性,其值可以是CONNECTING(0),OPEN(1),CLOSED(3)。

    • boolean send(in DOMString data)

    • void close()兩個(gè)方法,分別用于發(fā)送消息和關(guān)閉WebSocket連接

    onopen, onmessage, 和onclosee三個(gè)事件屬性,分別對(duì)open, message和close三個(gè)WebSocket事件。

    1、瀏覽器支持情況檢測(cè)

    檢測(cè)瀏覽器支持情況

    function loadDemo() {  
        if (window.WebSocket) {  
            //supported  
        } else {  
            // not supported  
        }  
    }

    2、WebSocket對(duì)象的創(chuàng)建和服務(wù)器連接

    要連接通信端點(diǎn),只需要?jiǎng)?chuàng)建一個(gè)新的WebSocket實(shí)例,并提供希望連接的對(duì)端URL。ws://和wss://前綴分別表示W(wǎng)ebSocket連接和安全的WebSocket連接。

    url = "ws://localhost:8080/echo";  w = new WebSocket(url);

    建立WebSocket連接時(shí),可以列出Web應(yīng)用能夠使用的協(xié)議。WebSocket構(gòu)造函數(shù)的第二個(gè)參數(shù)既可以是字符串,也可以是字符串組。

    w = new WebSocket(url, ["proto1", "proto2"]);

    假設(shè)proto1和proto2是定義明確、可能已注冊(cè)且標(biāo)準(zhǔn)化的協(xié)議名稱,它們能夠同時(shí)為客戶端和服務(wù)器端所理解。服務(wù)器會(huì)從列表中選擇首選協(xié)議。

    onopen = function(e) {  
        //確定服務(wù)器選擇的協(xié)議  
        log(e.target.protocol);  
    }

    3、添加事件監(jiān)聽(tīng)器

    WebSocket編程遵循異步編程模型;打開(kāi)socket后,只需等待事件發(fā)生,而不需要主動(dòng)向服務(wù)器輪詢,所以需要在WebSocket對(duì)象中添加回調(diào)函數(shù)來(lái)監(jiān)聽(tīng)事件。
    WebSocket對(duì)象有三個(gè)事件:open、close和message對(duì)應(yīng)有三個(gè)事件監(jiān)聽(tīng)器onopen,onmessage,onclose來(lái)處理連接的生命周期的每個(gè)階段,當(dāng)然還可以是onerror來(lái)監(jiān)聽(tīng)錯(cuò)誤,如以下示例所示。

    w.onopen = function() {  
        log("open");  
        w.send("send message");  
    }  
    w.onmessage = function(e) {  
        log(e.data);  
    }  
    w.onclose = function(e) {  
        log("closed");  
    }  
    w.onerror = function(e) {  
        log("error");  
    }

    4、發(fā)送消息

    當(dāng)socket處于打開(kāi)狀態(tài)(即onopen之后,onclose之前),可以用send方法來(lái)發(fā)送消息。消息發(fā)送完,可以調(diào)用close方法來(lái)終止連接,也可以不這么做,讓其保持打開(kāi)狀態(tài)。

    w.send();

    你可能想測(cè)算在調(diào)用Send()函數(shù)之前,有多少數(shù)據(jù)備份在發(fā)送緩沖區(qū)中。bufferAmount屬性表示已在WebSocket上發(fā)送但尚未寫入網(wǎng)絡(luò)的字節(jié)數(shù)。它對(duì)于調(diào)節(jié)發(fā)送速率很有用。

    document.getElementById("sendButton").onclick = function() {  
        if (w.bufferedAmount < bufferThreshold) {  
            w.send(document.getElementById("inputMessage").value);  
        }  
    }

    WebSocket API支持以二進(jìn)制數(shù)據(jù)的形式發(fā)送Blob和ArrayBuffer實(shí)例

    var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]);  
    w.send(a.buffer);

    常量-readyState屬性

    這些常量是readyState屬性的取值,可以用來(lái)描述WebSocket連接的狀態(tài)。

    ConstantValueDescription
    CONNECTING0The connection has not been opened yet.
    OPEN1The connection is open and ready for communication.
    CLOSING2The connection is in the process of closing.
    CLOSED3The connection has been closed, or the connection cannot be established.

    3.實(shí)例

    <!DOCTYPE html><html><head>
        <title>webSocket實(shí)例</title></head><body>
        <h2>webSocket實(shí)例</h2>
        <input type="text" id="text">
        <button type="" id="connect" onclick="connect()">建立連接</button>
        <button type="" id="send" onclick="send()">發(fā)送數(shù)據(jù)</button>
        <button type="" id="disconnect" onclick="disconnect()">斷開(kāi)連接</button>
        <p id="message"></p>
        <script type="text/javascript">
            var socket;        var readyState = ["正在連接","已經(jīng)連接","正在斷開(kāi)","已經(jīng)斷開(kāi)"];        var message = document.getElementById(&#39;message&#39;);        function connect(){
    
                try{                var url = &#39;ws:localhost/test&#39;;
                    socket = new webSocket(url);
                    message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    socket.onopen = function(){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    }
                    socket.onmessage = function(msg){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+&#39;<br>&#39;+ "接收數(shù)據(jù)" + msg.data +"</p>";
                    }
                    socket.onclose = function(){
                        message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
                    }
                }catch(exception){                // socket.onerror  = function(){
                        message.innerHTML += "<p>發(fā)生錯(cuò)誤!"+"</p>";                // }
                }
            }        function send(){
                var text = document.getElementById(&#39;text&#39;).value;            try{
                    socket.send(text);
                    message.innerHTML += "<p>發(fā)送數(shù)據(jù):" + text +"</p>";
                }catch(exception){
                    message.innerHTML += "<p>發(fā)送數(shù)據(jù)出錯(cuò)</p>";
                }
            }        function disconnect(){
                socket.close();
            }    </script></body></html>

    ?以上就是Html5 中的 WebSocket通信的內(nèi)容,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)(m.miracleart.cn)!


    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

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

    H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

    Is h5 same as HTML5? Is h5 same as HTML5? Apr 08, 2025 am 12:16 AM

    "h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

    Is H5 a Shorthand for HTML5? Exploring the Details Is H5 a Shorthand for HTML5? Exploring the Details Apr 14, 2025 am 12:05 AM

    H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

    H5 and HTML5: Commonly Used Terms in Web Development H5 and HTML5: Commonly Used Terms in Web Development Apr 13, 2025 am 12:01 AM

    H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

    Understanding H5 Code: The Fundamentals of HTML5 Understanding H5 Code: The Fundamentals of HTML5 Apr 17, 2025 am 12:08 AM

    HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

    What does H5 mean? What does H5 mean? Apr 04, 2025 am 12:10 AM

    H5 is the abbreviation of HTML5 and is the fifth version of HTML. H5 enhances the structure and semantics of web pages, and introduces new features such as video, audio, canvas drawing and geolocation APIs, making web page development richer and more efficient.

    HTML5: The Standard and its Impact on Web Development HTML5: The Standard and its Impact on Web Development Apr 27, 2025 am 12:12 AM

    The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

    HTML5 and H5: Understanding the Common Usage HTML5 and H5: Understanding the Common Usage Apr 22, 2025 am 12:01 AM

    There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

    See all articles