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

6次阅读

共计 1767 个字符,预计需要花费 5 分钟才能阅读完成。

如何应用 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('从新建设链接')
    }
  };
正文完
 0