C语言可以通过使用socket编程来实现一个简单的HTTP服务器。下面是一个使用C语言编写的基本的HTTP服务器示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_BUFFER_SIZE 1024
void handle_request(int client_socket) {
char buffer[MAX_BUFFER_SIZE];
memset(buffer, 0, sizeof(buffer));
// 读取客户端请求
read(client_socket, buffer, sizeof(buffer));
printf("Request:\n%s\n", buffer);
// 构建响应
char response[MAX_BUFFER_SIZE];
sprintf(response, "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<html><body><h1>Hello, World!</h1></body></html>");
// 发送响应给客户端
write(client_socket, response, strlen(response));
// 关闭客户端连接
close(client_socket);
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_address_length;
// 创建套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Failed to create socket");
exit(1);
}
// 设置服务器地址
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8080);
// 绑定套接字到服务器地址
if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("Failed to bind");
exit(1);
}
// 监听连接
if (listen(server_socket, 5) < 0) {
perror("Failed to listen");
exit(1);
}
printf("Server listening on port 8080...\n");
while (1) {
// 接受客户端连接
client_address_length = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr *)&client_address, &client_address_length);
if (client_socket < 0) {
perror("Failed to accept");
exit(1);
}
// 处理客户端请求
handle_request(client_socket);
}
// 关闭服务器套接字
close(server_socket);
return 0;
}
这个示例代码创建了一个简单的HTTP服务器,监听在本地8080端口。当有客户端连接时,它会读取客户端的请求并返回一个固定的HTML响应。你可以根据自己的需求修改handle_request
函数来处理不同的请求。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站