需要安裝ws包,安裝node教程在上篇文章中

服務端代碼 app.js
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const http = require("http");
//添加證書,ws和wss的主要差別就在這里
const keyPath=process.cwd()+'/ssl_certificate_key.key';
const certPath=process.cwd()+'/ssl_certificate.pem';
console.log(keyPath)
console.log(certPath)
const server = https.createServer({
cert: fs.readFileSync(certPath),
key: fs.readFileSync(keyPath)
});
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
/*ws.on('message', function incoming(message) {
console.log('received: %s', message);
});*/
setInterval(() => {
var data = {username:"hello"};
data = JSON.stringify(data);
var opt = {
host:'可以填寫域名或者IP',
port:'可以填寫也可以不填寫,阿里雲服務器注意開放80和443端口',
path:'如過host填寫IP這里可以寫域名+目錄文件,host填寫域名這里可以填寫路徑',
}
var body = '';
var req = https.request(opt, function(res) {
//console.log("response: " + res.statusCode);
res.on('data',function(data){
body += data;
}).on('end', function(){
//請求接口完畢后發送接口數據到客戶端
ws.send(body)
console.log(body)
});
}).on('error', function(e) {
console.log("error: " + e.message);
})
req.write(data);
req.end();
}, 10000)//10000=十秒
console.log(123);
ws.send('鏈接成功');
});
server.listen(9001);
客戶端文件 web.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .kuang{text-align: center;margin-top:200px;} #mess{text-align: center} </style> </head> <body> <div id="mess"></div> <script> if(window.WebSocket){ var ws = new WebSocket('wss://這里可以填寫域名或IP:9001'); ws.onopen = function(e){ console.log("連接服務器成功"); // 向服務器發送消息 ws.send("what`s your name?"); } ws.onclose = function(e){ console.log("服務器關閉"); } ws.onerror = function(){ console.log("連接出錯"); } // 接收服務器的消息 ws.onmessage = function(e){ let message = "message:"+e.data+""; console.log(message); } } </script> </body> </html>
服務端執行node app.js
訪問客戶端打開控制台效果如下

