gpt4 book ai didi

javascript - 使用node.js进行客户端服务器通信

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:11 25 4
gpt4 key购买 nike

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

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('');

运行 Node Helper.js 时,出现 { [Error: sockethang up] code: 'ECONNRESET' }

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

最佳答案

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

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 可以工作:

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");

关于javascript - 使用node.js进行客户端服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19700890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com