gpt4 book ai didi

C-服务器 : HTTP response missing new line

转载 作者:行者123 更新时间:2023-11-30 16:50:10 25 4
gpt4 key购买 nike

C-SERVER:
执行外部脚本:/script
存储在“vvv”和“vvv”中的脚本的响应被发送到客户端。

fp = popen("/script", "r");
fgets(vvv, 500, fp);

write(client_fd, vvv, sizeof(vvv) - 1);
close(client_fd);

/script的内容

#!/bin/sh
echo -e 'HTTP/1.1 200 OK\r\n';

使用netcat测试:

echo TEST | nc <ip> <port>
HTTP/1.1 200 OK

问题:它无法包含换行符,因此无法与网络浏览器一起使用。

C-服务器:

#include <arpa/inet.h>
#include <err.h>
#include <string.h>

char inn[100];

FILE *fp;
char vvv[100];

int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);

int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");

setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

int port = 85;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);

if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}

listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
size_t bytesRead = read(client_fd,inn,sizeof(inn) - 1);

fp = popen("/script", "r");
fgets(vvv, 500, fp);
printf(vvv);


write(client_fd, vvv, sizeof(vvv) - 1);
close(client_fd);
}
}

最佳答案

请注意,HTTP header 和内容由空行分隔。如果您根本不提供任何内容,情况也是如此。

此外,echo 已经在该行后面附加了一个换行符。使用 printf 代替:

#!/bin/sh
printf 'HTTP/1.1 200 OK\r\n';
printf '\r\n';
printf 'Content'; # provide some content

但这要求您现在需要从 fp 读取多行。添加一个额外的循环来读取 fp 中的每一行:

...

while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
size_t bytesRead = read(client_fd,inn,sizeof(inn) - 1);

fp = popen("/script", "r");

while (!feof(fp)) {
// be careful here to use `sizeof` instead of the harcoded `500`
fgets(vvv, sizeof(vvv), fp);
// only write the number of bytes read
write(client_fd, vvv, strlen(vvv));
printf(vvv);
}

close(client_fd);
}

...

还可以考虑使用 fread 而不是 fgets 来防止截断长行。

关于C-服务器 : HTTP response missing new line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315087/

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