Http服务器-第一步实现80端口服务

代码主要描述基本原理





#include <iostream>
#include <list>
#include <string>
#include <algorithm>
#include <vector>
#include <thread>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
/*
#include <functional>
#include "direct.h"
#include <map>
#include <memory>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <atomic>

#include <unordered_map>
*/

#include "winsock.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#pragma comment (lib,"wsock32")





int main()
{
	WSADATA wsadata;
	WORD wVersion = MAKEWORD(2, 0);
	WSAStartup(wVersion, &wsadata);



	int sock, length;
	length = sizeof(sockaddr);


	struct sockaddr_in server_ipaddr, client_ipaddr;
	memset(&server_ipaddr, 0, length);
	server_ipaddr.sin_family = AF_INET;
	server_ipaddr.sin_port = htons(80);
	server_ipaddr.sin_addr.s_addr = inet_addr("127.0.0.1");


	char buff[4096];  

	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	::bind(sock, (sockaddr *)&server_ipaddr, length);


	listen(sock, 100);



	char *head =

		"HTTP/1.0 200 OK\n"
		"Content-Type: text/html\n\n";
	
	 
		char *html =
			"<html><head><title>我的第一个 HTML 页面</title></head><body>"
	 "<p>body 元素的内容会显示在浏览器中。</p>"
	  "<p>title 元素的内容会显示在浏览器的标题栏中。</p>"
		"</body></html>";


	std::cout << "start server ok" << std::endl;
	int len,sock_client;
	while (1)
	{

		sock_client = accept(sock, (sockaddr *)&client_ipaddr, &length);

		len = recv(sock_client, buff, 4095, 0);
		 buff[len] = '\0';
		printf("%s", buff);

		send(sock_client, head, strlen(head), 0);
		send(sock_client, html, strlen(html), 0);

		closesocket(sock_client);
	}



	system("pause");

	return 0;
}

打开浏览器输入地址,就看到l响应

225544_E6uD_1391394.png

转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/744478

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值