我正在尝试用 C 编写一个简单的 Web 服务器。到目前为止,我可以接收连接并接收完整的消息。但是,根据 HTTP/1.0 协议,我希望能够在遇到“\r\n\r\n”序列时将信息发送回客户端。但是,当使用 Telnet 测试我的服务器时,当我输入“\r\n\r\n”时,服务器什么也不做,直到我在客户端上点击“^]”。我对 Apache 进行了测试,Apache 没有这个问题。所以我希望能得到一些关于如何模仿 Apache 行为的信息。我的代码添加在下面,但请记住,我还没有完成,也没有实现很多错误检查。谢谢!
main(){
int sock_fd = 0;
int client_fd = 0;
struct sockaddr_in socket_struct;
/*Creates the socket*/
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "%s: %s\n", getprogname(), strerror(errno));
exit(EXIT_FAILURE);
}/*Ends the socket creation*/
/*Populates the socket address structure*/
socket_struct.sin_family = AF_INET;
socket_struct.sin_addr.s_addr=INADDR_ANY;
socket_struct.sin_port =htons(port);
if (bind(sock_fd, (struct sockaddr*) &socket_struct, sizeof(socket_struct)) < 0)
{
fprintf(stderr, "%s: %s\n", getprogname(), strerror(errno));
exit(EXIT_FAILURE);
}//Ends the binding.
if (listen(sock_fd, 5) <0)
{
fprintf(stderr, "%s: %s\n", getprogname(), strerror(errno));
exit(EXIT_FAILURE);
}//Ends the listening function
if ( (client_fd = accept(sock_fd, NULL, NULL)) <0)
{
fprintf(stderr, "%s: %s\n", getprogname(), strerror(errno));
exit(EXIT_FAILURE);
}//Ends the accepting.
while ( (size = read(client_fd, msg, 1024)) > 0)
{
//size = recv(client_fd, msg, 1024, MSG_PEEK|MSG_WAITALL);
if ( (msg[size-4] == 13) && (msg[size-3] == 10)&&(msg[size-2] == 13) && (msg[size-1] == 10) )
{
char* buffer = (char *)malloc(sizeof("The msg was: ")+ sizeof(msg));
sprintf(buffer, "The msg was: %s", msg);
send(client_fd, buffer, sizeof("The msg was: ")+ sizeof(msg), MSG_OOB);
}
}//ends the while loop for receiving data
close(client_fd);
}