httpd的基本原理

代码
#include <sys/socket.h>
#include
<string.h>
#include
<netinet/in.h>
#include
<errno.h>


int main(int argc, char** argv)
{
int s, con;
struct sockaddr_in cliaddr, servaddr;

s
= socket(AF_INET, SOCK_STREAM, 0);
bzero(
&servaddr, sizeof(servaddr));
servaddr.sin_family
= AF_INET;
servaddr.sin_addr.s_addr
= htonl(INADDR_ANY);
servaddr.sin_port
= htons(8080);

bind(s, (
conststruct sockaddr *)&servaddr, sizeof(servaddr));

int err;
if((err = listen(s, 10)) ==-1)
printf(
"errno is %d\n", errno);

for(; ;){
//组塞地接受一个客户或连接
con = accept(s, 0, 0);

//recv request
char request[1024] = {0};
ssize_t ret
= recv(con, request, sizeof(request), 0);
printf(
"%s", request);

//whatever we recv, we send 200 reponse
{
char content[] ="<head><title>index.html</title></head><body>index.html</body>";
char reponse[512];
sprintf(reponse,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n%s", strlen(content), content);
ret
= send(con, reponse, strlen(reponse), 0);
}

close(con);}
}

大部分的代码来自 http://www.cppblog.com/kevinlynx/archive/2008/07/30/57521.html

我只改了一点

我在Ubuntu上用chrome测试 http://localhost:8080/index.html 

会输出以下结果:

posted @ 2011-02-04 21:47  lxgeek  阅读(581)  评论(0编辑  收藏  举报