所以我用C编写的基本服务器遇到了问题。每次我尝试向客户端发送少于6个字节时,客户端都不会显示我发送的字节。 send()调用没有失败。我已经在CURL和Postman上对此进行了测试,但都无法得到答复。
我将程序缩减为相关的位,因此您看到的结构在这里没有任何作用。
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void exit_with_error(const char *err);
#define MSG_SIZE 1028
typedef struct list_s
{
struct list_s *next;
char *title;
char *description;
int id;
} list_t;
int main(void)
{
char *client_name, msg[MSG_SIZE];
int server_socket, client_socket, r, id_count = 0, v = 1;
short server_port = 8080;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
list_t *todo_list = NULL;
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0)
exit_with_error("socket() failed");
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) < 0)
exit_with_error("setsockopt() failed");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_socket, (struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0)
exit_with_error("bind() failed");
if (listen(server_socket, 64) < 0)
exit_with_error("listen() failed");
printf("Server listening on port %d\n", server_port);
fflush(NULL);
while (1)
{
client_addr_len = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr *)&client_addr,
&client_addr_len);
if (client_socket < 0)
exit_with_error("accept() failed");
client_name = inet_ntoa(client_addr.sin_addr);
printf("%s ", client_name);
if (send(client_socket, "[", strlen("["), 0) < 0)
exit_with_error("send() failed");
close(client_socket);
}
close(server_socket);
return (0);
}
void exit_with_error(const char *err)
{
fprintf(stderr, "%s\n", err);
exit(1);
}
答案 0 :(得分:0)
我知道了-@DanielStenberg是正确的。显然,一旦我发送了一条带有正确的状态行和内容长度标头的消息,就可以在另一个send()调用中发送正文数据。