使用node.js进行客户端服务器通信 [英] client server communication using node.js
问题描述
在我的客户端计算机中,我有以下代码
In my client machine i have the following code
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
in my server side machine am using following 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正在获取 {[错误:套接字挂断]代码:'ECONNRESET'}
while running node helper.js am getting { [Error: socket hang up] code: 'ECONNRESET' }
它不会打印客户端中包含的data.tostring()。
it doesn’t print data.tostring() contained in the client side.
推荐答案
尝试在switch语句之前添加 res.writeHead(200);
。
Try adding res.writeHead(200);
before your switch statement.
此方法只能在消息上调用一次,并且必须在调用response.end()之前调用它。
This method must only be called once on a message and it must be called before response.end() is called.
来自 http:/ /nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers 。
更新
在讨论之后,以下 client.js
有效:
After our discussion the following client.js
works:
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");
这篇关于使用node.js进行客户端服务器通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!