간단 한 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 를 구축 하 는 일반적인 논리 에 부합 되 고 하나의 통 로 를 열 며 연결 채널 에서 주소,감청 채널 까지 채널 에서 요청 을 받 고 데 이 터 를 채널 을 통 해 보 냅 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
MVC의 심연를 보면 Trygve Reenskaug씨가 고안했다고 쓰여 있다. 뷰에 조작 오브젝트가 있는 경우와, 단순히 키보드나 마우스의 상태를 픽업하는 것을 고려하는 예이다. 그러나 잘 생각하면 이상하다. 예를 들어 키보드에...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.