C/C++ 实现简易HTTP服务器的示例
#include#include #include #include #pragmacomment(lib,"ws2_32.lib") #defineBUF_SIZE2048 #defineBUF_SMALL100 voidSend_404(SOCKETsock) { charProtocol[]="HTTP/1.0404BadRequest\r\n"; send(sock,Protocol,strlen(Protocol),0); closesocket(sock); } voidSendData(SOCKETsock,char*filename) { charProtocol[]="HTTP/1.1200OK\r\n"; charServerType[]="Server:MyWebServer\r\n"; charContentLen[]="Content-length:2048\r\n"; charContentType[]="Content-type:text/html\r\n"; charbuffer[BUF_SIZE]={0}; FILE*fp; if((fp=fopen(filename,"r"))!=NULL) { //传输头数据 send(sock,Protocol,strlen(Protocol),0); send(sock,ServerType,strlen(ServerType),0); send(sock,ContentLen,strlen(ContentLen),0); send(sock,ContentType,strlen(ContentType),0); //传输数据 while(fgets(buffer,BUF_SIZE,fp)!=NULL) send(sock,buffer,strlen(buffer),0); closesocket(sock); } } unsignedWINAPIRequestHandle(void*argv) { SOCKEThClntSock=(SOCKET)argv; charBuffer[BUF_SIZE]={0}; charMethod[BUF_SMALL]={0}; charFileName[BUF_SMALL]={0}; recv(hClntSock,Buffer,BUF_SIZE,0); //寻找HTTP请求头如果不为空则继续 if(strstr(Buffer,"HTTP/1")!=NULL) { //接着判断是否为GET请求方式 strcpy(Method,strtok(Buffer,"/")); if(strcmp(Method,"GET")!=0) { strcpy(FileName,strtok(0,"/")); printf("请求方式:%s请求文件:%s\n",Method,FileName); SendData(hClntSock,FileName); closesocket(hClntSock); return0; } } Send_404(hClntSock); closesocket(hClntSock); return-1; } intmain(intargc,char*argv[]) { WSADATAwsaData; SOCKETServerSock,ClientSock; SOCKADDR_INServerAddr,ClientAddr; WSAStartup(MAKEWORD(2,2),&wsaData); ServerSock=socket(PF_INET,SOCK_STREAM,0); memset(&ServerAddr,0,sizeof(ServerAddr)); ServerAddr.sin_family=AF_INET; ServerAddr.sin_addr.s_addr=htonl(INADDR_ANY); ServerAddr.sin_port=htons(80); bind(ServerSock,(SOCKADDR*)&ServerAddr,sizeof(ServerAddr)); listen(ServerSock,10); while(1) { HANDLEhThread; DWORDdwThreadID; intClientAddrSize; ClientAddrSize=sizeof(ClientAddr); ClientSock=accept(ServerSock,(SOCKADDR*)&ClientAddr,&ClientAddrSize); printf("请求客户端IP:%s-->端口:%d\n",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port)); hThread=(HANDLE)_beginthreadex(0,0,RequestHandle,(void*)ClientSock,0,(unsigned*)&dwThreadID); } closesocket(ServerSock); WSACleanup(); return0; }
以上就是C/C++实现简易HTTP服务器的示例的详细内容,更多关于C/C++实现简易HTTP服务器的资料请关注毛票票其它相关文章!