ノードにおける実時間データ通信の種々の方法js


導入


本稿では様々なリアルタイムデータ通信技術について述べる.
リアルタイム通信は、すべての接続されたクライアントが即座に、または、無視できる伝送遅延で情報を交換することができる通信のモードです.クライアントとサーバ間の情報をリアルタイムでやり取りすることができる様々な技術があります.

技法


ポーランド人ポーリング
  • サーバは、イベント
  • を送りました
  • ウェブソケット

  • ポーリング

  • はクライアントが常に一定の規則的な間隔でアップデートのためにサーバーを要求する「クライアントプル」アーキテクチャのタイプです.
  • クライアントは特定の時間を待ち、新しい更新プログラムをサーバーに要求します.
  • は、半二重または片方向通信の一種であり、一度に一方向の伝送しか許されない.
  • HTTPプロトコルに基づいています.
  • 高遅延伝送.
  • ブラウザのサポート:クライアント側で「ポーリング」更新を受信または送信するには、ブラウザのサポートがcaniuseで見つけることができるXmlHttpRequest JavaScript APIを使用します.
  • このテクニックをノードに実装しましょう.js
    1 )端末をオープンし、フォルダをポーリングする
    mkdir polling && cd polling
    
    2 )フォルダ内のNPMを初期化する
    npm init -y
    
    3 )アプリケーションを作成します.JSファイルといくつかのコードを書く.
    const express = require('express')
    const app = express()
    const port = 80
    
    app.use('/', express.static('public'));
    
    var data = "Real-Time Update 1";
    var number = 1;
    
    app.get('/', (req, res) => {
      res.send({"update": data})
    });
    
    var interval = setInterval(function(){
        data = "Real-Time Update "+number;
        console.log("SENT: "+data);
        number++;
    }, randomInteger(2,9)*1000);
    
    function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }  
    
    app.listen(port, () => {
      console.log(`Listening at http://localhost:${port}`)
    })
    
    4 )必要な依存関係やライブラリをインストールします.
    npm install --save express
    
    5 )パブリックフォルダを作成します.
    mkdir public && cd public
    
    6 )パブリックフォルダの中にHTMLフォルダを作成します.
    mkdir html && cd html
    
    7 )インデックスを作成する.パブリックフォルダの中のHTMLファイルとその中のコードを書きます.
    <html>
        <head>
            <title>Polling</title>
        </head>
        <body>
            <div id="updates"></div>
        </body>
        <script type="text/javascript">
    
            var interval = setInterval(function(){
                getUpdates();
            }, 5000);
    
            function getUpdates()
            {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", "/", true);
                xhr.onload = function (e) {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {                    
                        document.getElementById('updates').innerHTML = document.getElementById('updates').innerHTML + "Received: "+JSON.parse(xhr.responseText).update+"</br>";
                    }
                }
                };
                xhr.onerror = function (e) {
                    console.error(xhr.statusText);
                };
                xhr.send(null);
            }
        </script>
    </html>
    
    8 )アプリケーションを実行します.jsファイル
    //if you are inside html folder then go to your root project directory
    cd ../..
    
    //Now execute the app.js file
    node app.js
    
    ブラウザを開き、http://localhost/html/index.htmlにポイントします.
    ノードにポーリング技術を実装した.jsあなたが見ることができるように、それは伝送待ち時間が非常に高いです.

    2 .サーバ送信イベント

  • は、サーバーが即座に新しい情報を受け取るたびにクライアントにアップデートをプッシュする“サーバープッシュ”アーキテクチャのタイプです.
  • 最初のクライアントはハンドシェイク要求をサーバに送信します.ハンドシェークまたは接続を確立した後、クライアントはサーバーにデータを送信することができません.
  • は半二重または片方向通信の一種です.しかし、握手の後、サーバだけがデータを送ることができます.
  • HTTPプロトコルに基づいています.
  • は低遅延伝送を提供する.
  • クライアント側で「サーバー送信されたイベント」アップデートを受け取るか、送るために、私たちは、ブラウザ・サポートがcaniuseで見つかるEventSource JavaScript APIを使用するつもりです.
  • このテクニックをノードに実装しましょう.js
    1 )端末をオープンし、イベントを送信したフォルダサーバを作成する
    mkdir server-sent-events && cd server-sent-events
    
    2 )フォルダ内のNPMを初期化する
    npm init -y
    
    3 )アプリケーションを作成します.JSファイルといくつかのコードを書く.
    const express = require('express')
    const app = express()
    const port = 80
    
    app.use('/', express.static('public'));
    
    var data = "Real-Time Update 1";
    var number = 1;
    
    app.get('/server-sent-events', function(req, res) {
    
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        });
    
        var interval = setInterval(function(){
            data = "Real-Time Update "+number;
            console.log("SENT: "+data);
            res.write("data: " + data + "\n\n")
            number++;
        }, randomInteger(2,9)*1000);
    
        // close
        res.on('close', () => {
            clearInterval(interval);
            res.end();
        });
    })
    
    function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }  
    
    app.listen(port, () => {
      console.log(`Listening at http://localhost:${port}`)
    })
    
    4 )必要な依存関係やライブラリをインストールします.
    npm install --save express
    
    5 )パブリックフォルダを作成します.
    mkdir public && cd public
    
    6 )パブリックフォルダの中にHTMLフォルダを作成します.
    mkdir html && cd html
    
    7 )インデックスを作成する.パブリックフォルダの中のHTMLファイルとその中のコードを書きます.
    <html>
        <head>
            <title>Server Sent Events</title>
        </head>
        <body>
            <div id="updates"></div>
        </body>
        <script type="text/javascript">    
    
            var source = new EventSource('/server-sent-events')
    
            source.addEventListener('message', function(e) {            
                document.getElementById('updates').innerHTML = document.getElementById('updates').innerHTML + "Received: "+e.data+"</br>";
            }, false)
    
        </script>
    </html>
    
    8 )アプリケーションを実行します.jsファイル
    //if you are inside html folder then go to your root project directory
    cd ../..
    
    //Now execute the app.js file
    node app.js
    
    ブラウザを開き、http://localhost/html/index.htmlにポイントします.
    我々は、ノード内のイベントを送信するイベントを実装した.js我々は、“サーバーへのクライアント送信”の唯一の懸念は、このプロトコルを使用することができます.

    3 .ウェブソケット

  • それは一種の「サーバープッシュ」アーキテクチャです.
  • ハンドシェイクの後の
  • の両方のクライアントとサーバーは、いつでも情報を送受信することができます.
  • それは、両方のクライアントとサーバーが同時に情報を送受信する全二重または双方向通信の一種です.
  • はHTTP & TCP/IPプロトコルに基づいています.
  • は低遅延伝送を提供する.
  • クライアント側で「Webソケット」アップデートを受信または送信するには、WebSocket JavaScript APIを使用して、ブラウザサポートをcaniuseで見つけることができます.
  • このテクニックをノードに実装しましょう.js
    1 )端末を開き、フォルダを作成する
    mkdir websockets && cd websockets
    
    2 )フォルダ内のNPMを初期化する
    npm init -y
    
    3 )アプリケーションを作成します.JSファイルといくつかのコードを書く.
    const http = require('http')
    const express = require('express')
    const WebSocket = require('ws')
    const app = express()
    const port = 80
    
    app.use('/', express.static('public'));
    
    const server = http.createServer(app);
    const wss = new WebSocket.Server({ server })
    
    var data = "Real-Time Update 1";
    var number = 1;
    
    wss.on('connection', ws => {
    
      ws.on('message', message => {
        console.log(`Received message => ${message}`)
      })
    
      var interval = setInterval(function(){
        data = "Real-Time Update "+number;
        console.log("SENT: "+data);
        ws.send(data)
        number++;
      }, randomInteger(2,9)*1000);  
    
      ws.on('close', function close() {
        clearInterval(interval);
      });
    })
    
    function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }  
    
    server.listen(port, () => {
      console.log(`Listening at http://localhost:${port}`)
    })
    
    4 )必要な依存関係やライブラリをインストールします.
    npm install --save express
    npm install --save ws
    
    5 )パブリックフォルダを作成します.
    mkdir public && cd public
    
    6 )パブリックフォルダの中にHTMLフォルダを作成します.
    mkdir html && cd html
    
    7 )インデックスを作成する.パブリックフォルダの中のHTMLファイルとその中のコードを書きます.
    <html>
        <head>
            <title>Server Sent Events</title>
        </head>
        <body>
            <div id="updates"></div>
        </body>
        <script type="text/javascript">    
    
            const connection = new WebSocket('ws://localhost:80')
    
            connection.onmessage = e => {
                document.getElementById('updates').innerHTML = document.getElementById('updates').innerHTML + "Received: "+e.data+"</br>";
            }
    
        </script>
    </html>
    
    8 )アプリケーションを実行します.jsファイル
    //if you are inside html folder then go to your root project directory
    cd ../..
    
    //Now execute the app.js file
    node app.js
    
    ブラウザを開き、http://localhost/html/index.htmlにポイントします.
    ノードにwebソケット技術を実装した.js

    概要



    結論


    私たちがdisscussedしている最も使用されるテクニックがあります、これらから離れて、リアルタイムデータ伝送のために利用できるテクニックの何百もあります.
    プロジェクトはGitHubにあります.
    より多くの最新版のために、または私について来てください、または、GitHub.