1

我创建了一个简单的套接字连接,它向 node.js 应用程序发送请求并接收一些随机数据,然后发回数据,但它正确发送和接收数据,但不发回随机数据

char *httpbody;
struct addrinfo hints, *result;
const char *host = "localhost";
char user[512] = "test@gmail.com";
char pass[512] = "test";
char headers[512];
srand(time(NULL));

memset(&hints, 0, sizeof(hints));

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;

if (getaddrinfo(host, "3000", &hints, &result) != 0) {
    freeaddrinfo(result);
    perror("Could not resolve hostname.");
    exit(1);
}

int newsocket = socket(result->ai_family, result->ai_socktype, 0);
if (newsocket == -1) {
    perror("Could not create socket.");
    freeaddrinfo(result);
    close(newsocket);
    exit(1);
}

if (connect(newsocket, result->ai_addr, result->ai_addrlen) == -1) {
    perror("Could not connect.");
    freeaddrinfo(result);
    close(newsocket);
    exit(1);
}

sprintf(headers, "GET /auth?user=%s&pass=%s HTTP/1.1\r\n"
        "User-Agent: Device\r\n"
        "Accept-Language: de,en;q=0.7,en-us;q=0.3\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "Connection: Close\r\n\r\n", user, pass);

if ((send(newsocket, headers, strlen(headers), 0)) == -1) {
    perror("Could not send data.");
    freeaddrinfo(result);
    close(newsocket);
    exit(1);
}

char response[51201] = "";
recv(newsocket, response, 51200, 0);
response[strlen(response)] = '\0';

httpbody = strstr(response, "\r\n\r\n");
if (httpbody) {
    httpbody += 8;
}

int data = rand() % 255 + 1;

sprintf(headers, "GET /add_data?user=%s&data=%i&"
        "uid=%s HTTP/1.1\r\n"
        "User-Agent: Device\r\n"
        "Accept-Language: de,en;q=0.7,en-us;q=0.3\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "Connection: Close\r\n\r\n", user, data, httpbody);

if ((send(newsocket, headers, strlen(headers), 0)) == -1) {
    perror("Could not send data.");
    freeaddrinfo(result);
    close(newsocket);
    exit(1);
}

printf("done");

freeaddrinfo(result);
close(newsocket);

当我删除revc请求时,它工作正常并且没有显示任何错误,我完全迷失了

4

2 回答 2

1

检查这行代码:

recv(newsocket, response, 51200, 0);
response[strlen(response)] = '\0';`

recv 不返回以 null 结尾的数据,因此您不能使用 strlen 来确定数据的大小。您必须改用 recv 的返回值:

int data_size = recv(newsocket, response, 51200, 0);
于 2013-07-11T00:14:49.837 回答
0

每次在 HTTP 1.1 中指定“Connection: close”时,HTTP 连接都会结束,因此在您读取完来自服务器的响应后,套接字无效。

可能的解决方案是:

  • 从第一个请求中删除“连接:关闭”标头
  • 在你接收到响应后再次 Connect() 到服务器
于 2013-07-17T07:34:22.827 回答