websocket 云构建怎么建立日志在服务器和前端应用间的同步

呼啦星星星 -
websocket 云构建怎么建立日志在服务器和前端应用间的同步
如何使用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('重新建立链接')
    }
  };
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascriptnode.jswebsocket

扩展阅读

加个好友,技术交流

1628738909466805.jpg