让我先说这样做不是一个好主意。
但是,您可以生成一个 shell 并使用 web-sockets 或 XMLHttpRequests 将按键推送到生成的服务器进程。这是一个在 Windows 上运行的工作示例。不幸的是,我没有去连接/弄清楚 Ctrl+c。但是,你应该明白它的要点。
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;
}
}
});
});
编辑:实际上,这是一个工作示例的一部分。它缺少您捕获击键并将其发送到服务器的客户端。但是,它应该给你一个大致的想法。