ノードにおける実時間データ通信の種々の方法js
10709 ワード
導入
本稿では様々なリアルタイムデータ通信技術について述べる.
リアルタイム通信は、すべての接続されたクライアントが即座に、または、無視できる伝送遅延で情報を交換することができる通信のモードです.クライアントとサーバ間の情報をリアルタイムでやり取りすることができる様々な技術があります.
技法
ポーランド人ポーリング
ポーリング
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 .サーバ送信イベント
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 .ウェブソケット
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.
Reference
この問題について(ノードにおける実時間データ通信の種々の方法js), 我々は、より多くの情報をここで見つけました https://dev.to/kalpitrathore/various-ways-of-real-time-data-communication-in-node-js-1h2bテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol