C++实现简单http服务器

只要懂socket套接字,http请求和响应的格式,就行了

C++实现简单http服务器_第1张图片

#include 
#include 
#include 
#include 
#pragma comment(lib,"ws2_32.lib")
using namespace std;

#define PORT 9999

int main(){
	SOCKET sock;
	SOCKET connfd;
	WORD ver = MAKEWORD(2,2);//版本
	WSADATA dat;
	WSAStartup(ver, &dat);

	sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if (sock == -1)
	{
		return false;
	}
	
	struct sockaddr_in sever_address;
	memset(&sever_address,0,sizeof(sever_address));
	sever_address.sin_family = AF_INET;
	sever_address.sin_addr.s_addr =htonl(INADDR_ANY);
	sever_address.sin_port = htons(PORT);

	int ret = bind(sock, (struct sockaddr*)&sever_address,sizeof(sever_address));
	assert(ret != -1);

	ret = listen(sock,10);
	assert(ret != -1);
	cout<<"wait\n";
	while (1)
	{
		struct sockaddr_in client_address;
		int len=sizeof client_address;
		connfd=accept(sock,(sockaddr*)&client_address,&len);
		char buf[1024];
		int n=recv(connfd,buf,sizeof buf,0);
		buf[n]='\0';
		printf("recv:\n%s\n",buf);
		char head[]="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";

		string text1="\n\n\n菜鸟教程(runoob.com)"</span><span class="token punctuation">;</span>
		string text2<span class="token operator">=</span><span class="token string">"\n\n

我的第一个标题

\n

我的第一个段落。

\n\n\n"
; string text=text1+text2; send(connfd,head,strlen(head),0); send(connfd,text.c_str(),strlen(text.c_str()),0); printf("send:\n"); cout<<head<<text<<endl; closesocket(connfd); } closesocket(sock); getchar(); }

你可能感兴趣的:(C++)