간단 한 http server(Linux,gcc)를 만 듭 니 다.

16331 단어 server

  
    
#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
Server: HTTP Server BY Zhengsq
"
" \r
Content-Type: text/html;charset=gb2312\r
\r
"
" <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
" ;
if (pthread_create( & t, & attr, thread_run, NULL) != 0 )
std::cerr
<< " Unable to launch a thread
" ;
if (pthread_attr_destroy( & attr) != 0 )
std::cerr
<< " Unable to launch a thread
" ;
if (pthread_detach(t) != 0 )
std::cerr
<< " Unable to launch a thread
" ;
}

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

상기 코드 는 매우 간단 합 니 다.socket,메 인 스 레 드 sleep 를 처리 하기 위해 스 레 드 를 엽 니 다.
위 에서 코드 는 다음 과 같 습 니 다.스 레 드 를 기본 과정 으로 열 고 스 레 드 의 실행 함수 에 함수 포인터 void*(*)(void*)를 사 용 했 습 니 다.
socket 서버 단 을 여 는 일반적인 절차:
1、int fd = socket(AF_INET, SOCK_STREAM,0),socket 의 handle(또는 포인터 라 고 할 수 있 음)을 얻 습 니 다.
2、bind(fd, &addr, sizeof(addr));
3、listen(fd, 4);
4.반복 해서 요청 수락 accept()
위의 절차 도 하나의 server 를 구축 하 는 일반적인 논리 에 부합 되 고 하나의 통 로 를 열 며 연결 채널 에서 주소,감청 채널 까지 채널 에서 요청 을 받 고 데 이 터 를 채널 을 통 해 보 냅 니 다.

좋은 웹페이지 즐겨찾기