编写一个简单的http server(Linux, gcc)

#include <iostream>
#include
<pthread.h>
#include
<stdlib.h>
#include
<stdio.h>
#include
<sys/socket.h>
#include
<string.h>
#include
<netinet/in.h>
#include
<arpa/inet.h>

using namespace std;
bool stop = false;


void *thread_run(void *arg)
{
struct sockaddr_in addr;
memset(
&addr, 0, sizeof(addr));
int fd;
addr.sin_family
= AF_INET;
addr.sin_port
= htons(8081);
addr.sin_addr.s_addr
= INADDR_ANY;
if((fd = socket(AF_INET, SOCK_STREAM, 0))==-1)
{
std::cerr
<<"Unable to Open the Socket"<<endl;
stop
= true;
return NULL;
}
if (bind(fd, (struct sockaddr*)(&addr), sizeof(addr)) != 0)
{
std::cerr
<<"Unable to bind the Socket"<<endl;
stop
= true;
return NULL;
}
if (listen(fd, 50) == -1)
{
std::cerr
<<"Unable to listen the Socket"<<endl;
stop
= true;
return NULL;
}
while(true){
sockaddr client_addr;
unsigned
int nLength;
int fdc = accept(fd, &client_addr, &nLength);
if (fdc == -1){
cerr
<<"Unable to Connect with the client"<<endl;
return NULL;
}
else{
char *request = new char[1000];
memset(request,
0, 1000);
read(fdc, request,
1000);
cout
<<request<<endl;
char buf[] = "HTTP/1.1 200 OK\r\nServer: HTTP Server BY Zhengsq"
"\r\nContent-Type: text/html;charset=gb2312\r\n\r\n"
"<h1>This is The Server By zhengsq</h1>";
write(fdc, buf, strlen(buf));
close(fdc);
delete[] request;
}
}
}

void child_thread()
{
pthread_t t;
pthread_attr_t attr;
if (pthread_attr_init(&attr) != 0)
std::cerr
<< "Unable to launch a thread\n";
if(pthread_create(&t, &attr, thread_run, NULL) != 0)
std::cerr
<< "Unable to launch a thread\n";
if(pthread_attr_destroy(&attr) != 0)
std::cerr
<< "Unable to launch a thread\n";
if(pthread_detach(t) != 0)
std::cerr
<< "Unable to launch a thread\n";
}

int main() {
child_thread();
while(!stop)
{
sleep(
1000);
}
return 0;
}

上述代码非常简单,专门开启一个线程用于处理socket,主线程sleep

上面到代码包括:开启线程到基本过程,注意线程的执行函数用到了函数指针 void *(*)(void *)

socket开启server端的一般步骤:

1、int fd = socket(AF_INET, SOCK_STREAM, 0),得到一个socket的handle(或者可以称之为指针)

2、bind(fd, &addr, sizeof(addr));

3、listen(fd, 4);

4、循环接受请求accept()

上面到步骤也符合建立一个server的一般逻辑,开辟一个通道,绑定通道到地址,监听通道,从通道接受请求,把数据通过通道送走……

posted @ 2011-03-21 22:33  霞光照耀  阅读(1895)  评论(0编辑  收藏  举报