我需要使用套接字在C中编写一个简单的HTTP Web服务器。到目前为止,我已经建立了套接字连接并且可以接收输入(使用fdopen
将套接字附加到FILE *
和fgets
之后),但是我不知道如何在何时停止阅读我得到\r\n\r\n
。到目前为止,我已经尝试将位置与strstr
匹配,但它似乎没有效果。当满足双重换行时,什么是终止读取的正确方法?
这是我目前代码的一部分:
char buf[BUFSIZE];
int read_fd = client_fd; //client_fd is the connecting client socket
int write_fd = dup2(client_fd,1); // duplicate the file descriptor
// Wrap the socket file descriptor using FILE* file handles,
// for both reading and writing.
FILE *read_fh = fdopen(read_fd, "r");
FILE *write_fh = fdopen(write_fd, "w");
int done = 0;
int result = 1;
while (!done) {
// Read one line from the client
if (!fgets(buf, BUFSIZE, read_fh)) {
break; // connection was interrupted?
}
char *cr = strstr(buf, "\r\n\r\n");
if (cr) {
fprintf(write_fh, "%s", buf);
done=1;
}
}