我有一个nodejs服务器,它通过模块'express'接收POST请求,我需要使用C ++发送POST请求,我的客户端 connect()和 send()函数返回一个数字> 0,但我的服务器没有收到任何内容,并且没有错误。 这是我的服务器代码和我的C ++代码,请帮助我,谢谢大家!(我的服务器运行良好,因为当我使用js发送请求时,它可以很好地接收请求。)
服务器代码:
app.post('/fps', function(req, res){
var fpsFilename = "./native/Data/FpsFile.txt";
console.log('execute the imagequality program');
var exec = require('child_process').exec;
console.log('in fps post');
exec('./native/fps ' + fpsFilename, function(err, data, stderr) {
if(data.length > 1) {
res.json({fps : data});
} else {
console.log('fps file trans error');
}
if(err) {
console.info('stderr from fps:'+stderr);
}
});
});
我的C ++代码:
#define IPSTR "127.0.0.1"
#define PORT 4001
#define BUFSIZE 4096
int MyBasicServerConnector::TestConnect()
{
int sockfd,ret,i ,h;
struct sockaddr_in servaddr;
char str1[4096], str2[2048], buf[BUFSIZE], *str;
socklen_t len;
fd_set t_set1;
struct timeval tv;
int isConneted = 0;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
printf("---------------------socket error!\n");
exit(0);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, IPSTR, &servaddr.sin_addr) <= 0 )
{
printf("---------------------inet_pton error!\n");
exit(0);
}
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
printf("---------------------connect error!\n");
exit(0);
}
else
{
isConneted = 1;
std::cout <<"---------------------connect success"<<endl;
}
memset(str2, 0, 2048);
//strcat(str2, "name = x\n");
//strcat(str2, "code = x");
//str=(char *)malloc(128);
len = strlen(str2);
//sprintf(str, "%d", len);
memset(str1, 0, 4096);
strcat(str1, "POST /fps HTTP/1.1 \r\n");
strcat(str1, "Host: 127.0.0.1:4001\r\n");
strcat(str1, "Connection: keep-alive\r\n");
strcat(str1, "Content-Length: 7\r\n");
strcat(str1, "Accept: */*\r\n");
strcat(str1, "Origin: http://127.0.0.1:4001\r\n");
strcat(str1, "X-Requested-With: XMLHttpRequest\r\n");
strcat(str1, "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36\r\n");
strcat(str1, "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n");
strcat(str1, "Referer: http://127.0.0.1:4001/\r\n");
strcat(str1, "Accept-Encoding: gzip, deflate, br\r\n");
strcat(str1, "Accept-Language: en-US,en;q=0.8\r\n");
if (isConneted > 0)
{
if(send(sockfd,str1 ,strlen(str1),MSG_NOSIGNAL)>0)
{
cout<<"ok\n";
}
else
{
cout<<"xx\n";
}
}
close (sockfd);
return 0;
}
答案 0 :(得分:0)
我建议您通过阅读standard来实际研究HTTP的工作方式。您的帖子中有几个错误。最明显的是:
HTTP/1.1
后面不应有空格\r\n
)