linux 使用node 完成websocket 实时推送 wss篇
需要安装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
访问客户端打开控制台效果如下