客户端服务器通信使用node.js

在我的客户端机器中,我有以下代码

client.js var fs = require('fs'); var http = require('http'); var qs = require('querystring'); var exec = require('child_process').exec; var server = http.createServer(function(req, res) { switch(req.url) { case '/vm/list': getVms(function(vmData) { res.end(JSON.stringify(vmData)); }); break; case '/vm/start': req.on('data', function(data) { console.log(data.toString()) exec('CALL Hello.exe', function(err, data) { console.log(err) console.log(data.toString()) res.end(''); }); }); break; } }); server.listen(9090); console.log("Server running on the port 9090"); 

在我的服务器端机器使用以下helper.js

 var options = { host: '172.16.2.51', port: 9090, path: '/vm/start', method: 'POST' }; var req = http.request(options, function(res) { res.on('data', function(d) { console.log(d.toString()); }); }); req.on('error', function(e) { console.error(e); }); req.end(''); 

而运行节点helper.js得到{ [Error: socket hang up] code: 'ECONNRESET' }

它不打印客户端中包含的data.tostring()。

尝试添加res.writeHead(200); 在你的switch语句之前。

该方法只能在消息中调用一次,并且必须在调用response.end()之前调用该方法。

http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers

更新

经过我们的讨论,以下client.js作品:

 var fs = require('fs'); var http = require('http'); var qs = require('querystring'); var exec = require('child_process').exec; var server = http.createServer(function(req, res) { switch(req.url) { res.writeHead(200); case '/vm/list': getVms(function(vmData) { res.end(JSON.stringify(vmData)); }); break; case '/vm/start': req.on('data', function(data) { console.log(data.toString()) exec('CALL Hello.exe', function(err, data) { console.log(err) console.log(data.toString()) }); }); req.on('end', function() { res.end(''); }); break; } }); server.listen(9090); console.log("Server running on the port 9090");