express socket.io 实现实时数据交互

背景

通过node调用生产环境脚本或命令,打印日志并实时传输到前端页面显示

环境配置

  • 生产环境 linux系统
  • node v8.12.0
  • express v4.16.3
  • socket.io v2.3.0
  • socket.io-client v2.3.0
  • 前端框架 angular6

代码实现

app.js

var express = require('express');
var server = express();
var httpServer = require('http').Server(server);
var io = require('socket.io')(httpServer);io.on("connection", (socket) => {socket.on('disconnect', function () {console.log('disconnected');});})io.of('log').on('connect', (socket) => {console.log('log connect');// socket.nsp.emit('message', '日志已连接');
})httpServer.listen(8080, function () {logger.info("启动端口:" + port);
});
router.get('/api/k8s/log', function (req, res, next) {try {let log$ = Sockets.io.of('/log');// var ls = spawn(path.join('log.sh'));// var ls = spawn("kubectl", ['logs', '-f', 'peer0-org1-7888c9696b-zjqdd', 'peer', '-n', 'baas']);// kubectl logs -f peer0-org1-7888c9696b-zjqdd peer -n baas// 生产环境脚本位置var ls = spawn("sh",["/bin/log.sh"]);// var ls = spawn(path.join('log.bat'));ls.stdout.on('data', function (data) {let buffer = Buffer.from(data);logger.warn('>>>>>>',buffer.toString('utf-8'))log$.emit("message", buffer.toString('utf-8'));});ls.stderr.on('data', (data) => {logger.error(`stderr: ${data}`);// 传输数据log$.emit("message", data);});ls.on('exit', function (code) {log$.emit("message", "socket-end");});ls.on('close', function (code) {logger.warn('>>>close', code)log$.emit("message", "socket-end");});} catch (error) {logger.error(error)}res.send({ code: 200, data: {} });})

client使用方法

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import * as io from "socket.io-client";@Injectable({providedIn: "root",
})
export class MessageSocketService {socket: SocketIOClient.Socket;connect(url) {if(this.socket) this.socket.disconnect();return new Observable((observer) => {// 初始化this.socket = io(url);// 接收消息this.socket.on("message", (data) => {observer.next(data);});});}
}
  getLog() {let url =location.port == "4200" ? "http://www.baoli.com:8080/log" : "/log";this.http.get("/api/k8s/log").subscribe((d) => {});this.socketService$ = this.socketService.connect(url).subscribe((d: any) => {this.datas.push(d.toString());if (d == "socket-end") {this.isDataLoading = false;console.log("日志传输完成!");}// if (this.isRendering) {//  requestAnimationFrame(this.scroll.bind(this));// }});}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部