websocket是客戶端(client)和服務端(server)雙向連結的通道,和http不同的是http服務端依賴客戶端
參考:
// 進入資料夾後建立初始package.json
npm init -y
npm install ws
// index.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 8080
});
wss.on('connection', function connection(ws) {
console.log('server connection')
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
npm install nodemon
// 成功後的網址
ws://localhost:8080/
// ws.js
const ws = new WebSocket('ws://localhost:8080/')
nodemon ws.js 啟動