如何在浏览器中模拟linux终端?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (230)

我已经阅读了关于Fabrice Bellard在浏览器中的linux模拟。

今天我偶然发现了这个网站,他们在浏览器中模拟完整的linux终端,我可以运行python,perl等。我知道他们在node.js上运行他们的站点,但我无法弄清楚他们是如何精确地模拟终点站的,有人能给出点指点建议吗?

提问于
用户回答回答于

你可以生成一个shell并使用web-sockets或XMLHttpRequests将按键压入生成的服务器进程:

  require("underscore");

  var Server = {},
      express = require("express"),
      path = require("path"),
      sys = require("sys"),
      application_root = __dirname;

  global.Server = Server;
  Server.root = application_root;
  global.app = express();

  Server.setup = require("./lib/setup.js").setup({
    //redis: require("./lib/redis-client").createClient(),
    app: app, 
    //mongoose : require("mongoose"),
    io : require("socket.io"),
    express : express,
    port: 1773,
    paths : {
      views :  path.join(application_root,"app","views"),
      root : path.join(application_root,"public"),
      controllers : path.join(application_root,"app","controllers"),
      models : path.join(application_root,"app","models")
    }
  });

  var proc = require('child_process'),
      cmd;

  app.socket.on('connection', function(socket) {
    if (!cmd) {
      //console.log('spawning cmd');
      cmd = proc.spawn('cmd');

      //console.log(cmd?'CMD started':'CMD not started');

      if (cmd.stdout) {
        //console.log('stdout present');
        cmd.stdout.on('data',function(data) {
          if (data) {
            //console.log("data: "+data);
            socket.emit('cmd', ""+data);
          }
        });
      }
      if (cmd.stderr) {
        cmd.stderr.on('data', function(data) {
          //console.log('stderr present');
          if (data) {
            socket.emit('cmd', ""+data);
          }
        });
      }

      cmd.on('exit', function() {
        //console.log('cmd exited');
        socket.emit('cmd', '[CMD Shutdown]');
        if (cmd) {
          cmd.kill();
          cmd = null;
        }
      });
    }

    socket.on('sendCmd', function(data) {
      if (data && data.buffer) {
        var kB = data.buffer.replace("\r","\n");
        if (cmd && cmd.stdin) {
          cmd.stdin.write(kB);
        }
      }
    });

    socket.on('disconnect', function() {
      console.log('connection closed');
      if (cmd) {
        cmd.stdin.end(); //.kill();
        if (cmd) {
          cmd.kill();
          cmd = null;
        }
      }
    });
  });

扫码关注云+社区

领取腾讯云代金券