如何应用websocket实现云端和前端的日志同步
背景:首先在应用云构建平台时,会实时通过前端通知你运行在云端的援用构建日志,那这个实时同步怎么实现呢,当然是websocket,就拿我目前实现的服务端nodejs 来讲
1 node端websocket实现
var WebSocket = require("ws");//建设websocket连贯 async connectSocket() { const { SET_WS, WATCH_CONFIG } = app const this_ = this try { const wss = new WebSocket.Server({ port: 8112 }); wss.on("connection", ws => { ws.on('message', (message, req) => { if (message == 'start') { //这里能够把ws设置到全局变量中,后续进行机会close() //这里就可通过node watch来把ws中构建内容写入服务器文件同时开启监听逐行同步给前端,其中logPath为构建日志配置存储的目录 const { WATCH } = WATCH_CONFIG(logPath) WATCH(ws) } else if (message == 'close') { ws?.terminate() } }); }); wss.on('error', (e) => { this.logger.info('error', e); }) wss.on('message', (str) => { this.logger.info('onmessage-----', str) }) wss.on('close', (code, message) => { this.logger.info('ws_close', code, message); }); } catch (error) { this.logger.info('ws_close', `${error}`); } }
2 node端监听文件的实现
const WATCH_CONFIG = (filePath) => { console.log('------------------', filePath) const WATCH = (ws) => { //先输入以后的所有日志 fs.readFile(filePath, 'utf-8', function (err, data) { if (err) { ws.send('读取谬误:', err) } else { ws.send(data) } }); fs.watch(filePath, (eventType, file) => { if (file && eventType === "change") { fs.readFile(filePath, 'utf-8', function (err, data) { if (err) { ws.send('读取谬误:', err) } else { ws.send(data) } }); } }) } const CLEAR = () => { fs.writeFile(filePath, '', () => { console.log('清空步骤日志结束' + filePath) }) } return { WATCH, CLEAR }}
3 前端实现
const syncLogs = () => { const connectCallback = () => { ws = new WebSocket('ws://xxx.com:8112'); ws.onopen = function (e) { console.log('连贯服务器胜利', ws); // 向服务器发送音讯,服务端能够依据这个start进行辨认身份 ws.send('start'); }; ws.onclose = function (e) { console.log('服务器敞开', e); }; ws.onerror = function (e) { console.log('连贯出错', e); message.error('服务端连贯出错,请从新点击获取日志'); ws = null; }; // 接管服务器的音讯 ws.onmessage = function (message) { console.log('..........', message); //这里将message通过react试试显示到容器中就行了 }; }; if (ws) { connectCallback(); } else { dispatch('从新建设链接') } };