根据请求的URI和HTTP方法,获取相应的资源,如HTML文件、图片、CSS文件等。C语言 window
时间: 2024-02-11 09:09:03 浏览: 113
获取请求的URI和HTTP方法,可以通过解析HTTP请求头中的信息来实现。在Windows环境下,可以使用Winsock库来实现TCP套接字通信,使用WinAPI函数来读取请求头中的信息,使用C标准库函数来读取文件内容。
以下是一个简单的实现示例,仅供参考:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define BUFFER_SIZE 1024
int main() {
WSADATA wsaData;
SOCKET listenSocket, clientSocket;
struct sockaddr_in serverAddr, clientAddr;
int serverPort = 80;
int addrLen = sizeof(clientAddr);
char buffer[BUFFER_SIZE], requestMethod[BUFFER_SIZE], requestUri[BUFFER_SIZE], filePath[BUFFER_SIZE];
FILE *fp;
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("Failed to initialize Winsock.\n");
return 1;
}
// 创建TCP套接字
if ((listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
printf("Failed to create socket.\n");
WSACleanup();
return 1;
}
// 绑定套接字到指定的IP地址和端口号
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(serverPort);
if (bind(listenSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("Failed to bind socket.\n");
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 监听连接请求
if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
printf("Failed to listen on socket.\n");
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 接受客户端连接请求
while (1) {
printf("Waiting for client connection...\n");
if ((clientSocket = accept(listenSocket, (struct sockaddr*)&clientAddr, &addrLen)) == INVALID_SOCKET) {
printf("Failed to accept client connection.\n");
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 读取HTTP请求头信息
memset(buffer, 0, BUFFER_SIZE);
recv(clientSocket, buffer, BUFFER_SIZE, 0);
sscanf(buffer, "%s %s", requestMethod, requestUri);
// 根据请求的URI和HTTP方法获取相应的资源
if (strcmp(requestMethod, "GET") == 0) {
if (strcmp(requestUri, "/") == 0) {
strcpy(filePath, "index.html");
} else {
strcpy(filePath, requestUri + 1);
}
fp = fopen(filePath, "r");
if (fp == NULL) {
printf("Failed to open file %s.\n", filePath);
closesocket(clientSocket);
continue;
}
// 读取文件内容并发送HTTP响应
memset(buffer, 0, BUFFER_SIZE);
sprintf(buffer, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
send(clientSocket, buffer, strlen(buffer), 0);
while (!feof(fp)) {
memset(buffer, 0, BUFFER_SIZE);
fread(buffer, 1, BUFFER_SIZE, fp);
send(clientSocket, buffer, strlen(buffer), 0);
}
fclose(fp);
} else {
// 处理不支持的HTTP方法
printf("Unsupported HTTP method: %s.\n", requestMethod);
closesocket(clientSocket);
continue;
}
// 关闭与客户端的连接
closesocket(clientSocket);
}
// 关闭监听套接字
closesocket(listenSocket);
// 清理Winsock库
WSACleanup();
return 0;
}
```
该示例仅实现了获取请求的URI和HTTP方法以及根据请求的URI获取相应的资源,并发送HTTP响应的功能。实际应用中,还需要考虑并发连接请求、处理非法请求等问题。
阅读全文