欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C/C++ 实现简易HTTP服务器的示例

时间:2021-04-13 09:14:58|栏目:C代码|点击:
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

#define BUF_SIZE 2048
#define BUF_SMALL 100

void Send_404(SOCKET sock)
{
	char Protocol[] = "HTTP/1.0 404 Bad Request\r\n";
	send(sock, Protocol, strlen(Protocol),0);
	closesocket(sock);
}

void SendData(SOCKET sock, char *filename)
{
	char Protocol[] = "HTTP/1.1 200 OK\r\n";
	char ServerType[] = "Server:MyWebServer\r\n";
	char ContentLen[] = "Content-length:2048\r\n";
	char ContentType[] = "Content-type:text/html\r\n";
	char buffer[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);
	}
}

unsigned WINAPI RequestHandle(void *argv)
{
	SOCKET hClntSock = (SOCKET)argv;

	char Buffer[BUF_SIZE] = { 0 };
	char Method[BUF_SMALL] = { 0 };
	char FileName[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);
			return 0;
		}
	}

	Send_404(hClntSock);
	closesocket(hClntSock);
	return -1;
}

int main(int argc,char * argv[])
{
	WSADATA wsaData;
	SOCKET ServerSock, ClientSock;
	SOCKADDR_IN ServerAddr, 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)
	{
		HANDLE hThread;
		DWORD dwThreadID;
		int ClientAddrSize;

		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();
	return 0;
}

上一篇:C++用easyx图形库实现障碍跑酷小游戏

栏    目:C代码

下一篇:深入解析int(*p)[]和int(**p)[]

本文标题:C/C++ 实现简易HTTP服务器的示例

本文地址:http://www.codeinn.net/misctech/100485.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有