编写一个简单的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的一般逻辑,开辟一个通道,绑定通道到地址,监听通道,从通道接受请求,把数据通过通道送走……

转载于:https://www.cnblogs.com/lovelyxia/archive/2011/03/21/1990808.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值