代码主要描述基本原理
#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响应