实验四 Web服务器2
Web服务器的客户端服务器
web_server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
void handle_client(int client_socket) {
char buffer[BUFFER_SIZE];
ssize_t bytes_received;
// 接收客户端请求
bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0);
if (bytes_received < 0) {
perror("从套接字读取数据时出错");
close(client_socket);
exit(EXIT_FAILURE);
}
// 解析HTTP请求
if (strstr(buffer, "GET") == NULL) {
fprintf(stderr, "仅支持GET请求。
");
} else {
// 构造HTTP响应
const char *response = "HTTP/1.1 200 OK
"
"Content-Type: text/plain
"
"
"
"你好,这是一个简单的Web服务器!
";
send(client_socket, response, strlen(response), 0);
}
// 关闭连接
close(client_socket);
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_size = sizeof(struct sockaddr_in);
// 创建套接字
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
perror("创建套接字时出错");
exit(EXIT_FAILURE);
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
// 将套接字绑定到地址和端口
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("绑定套接字时出错");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_socket, 10) == 0) {
printf("服务器正在监听端口 %d...
", PORT);
} else {
perror("监听套接字时出错");
exit(EXIT_FAILURE);
}
while (1) {
// 接受连接
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &addr_size);
if (client_socket < 0) {
perror("接受连接时出错");
exit(EXIT_FAILURE);
}
// 处理客户端请求
handle_client(client_socket);
}
// 关闭服务器套接字
close(server_socket);
return 0;
}
web_client.c
e <unistd.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
// 创建套接字
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
perror("创建套接字时出错");
exit(EXIT_FAILURE);
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
perror("设置服务器地址时出错");
exit(EXIT_FAILURE);
}
// 连接到服务器
if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("连接服务器时出错");
exit(EXIT_FAILURE);
}
// 构造HTTP GET请求
const char *request = "GET / HTTP/1.1
"
"Host: localhost
"
"Connection: close
"
"
";
send(client_socket, request, strlen(request), 0);
// 接收并打印服务器响应
ssize_t bytes_received;
while ((bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
fwrite(buffer, 1, bytes_received, stdout);
}
// 关闭套接字
close(client_socket);
return 0;
}
运行结果
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...