原文地址
github項目地址html
WebSocket是一種在單個TCP鏈接上進行全雙工通訊的協議。
使得客戶端和服務器之間的數據交換變得更加簡單,容許服務端主動向客戶端推送數據。
在WebSocket API中,瀏覽器和服務器只須要完成一次握手,二者之間就直接能夠建立持久性的鏈接,並進行雙向數據傳輸。
WebSocket與HTTP對比圖
git
const ws = new WebSocket('ws://localhost:8888'); ws.onopen = () => { console.log('WebSocket onopen'); } ws.onmessage = e => { console.log('WebSocket onmessage'); console.log('WebSocket message received:', e); console.log('WebSocket data received:', e.data); } ws.onclose = e => { console.log("WebSocket onclose"); };
const Koa = require('koa'); const WebSocket = require('ws'); const app = new Koa(); const ws = new WebSocket.Server({port: 8888}); ws.on('connection', ws => { console.log('server connection'); ws.on('message', msg => { console.log('server receive msg:', msg); }); ws.send('Information from the server'); }); app.listen(3000);
客戶端
github
服務端web