实验四 Web服务器2

随笔2个月前发布 简有米
40 0 0

基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用Linux Socket实现:

Web服务器的客户端服务器,提交程序运行截图
实现GET即可,请求,响应要符合HTTP协议规范
服务器部署到华为云服务器,浏览器用本机的
把服务器部署到试验箱。(加分项)

web服务器与客户端

web_server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

void handle_client(int client_socket) {
    char response[] = "HTTP/1.1 200 OK
Content-Type: text/html

<html><body><h1>Hello, this is a simple web server!</h1></body></html>
";
    send(client_socket, response, strlen(response), 0);
    close(client_socket);
}

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8080);
    
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
  
    while (1) {
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
            perror("accept");
            exit(EXIT_FAILURE);
        }
        handle_client(new_socket);
    }
    return 0;
}

web_client.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

int main() {
    struct sockaddr_in serv_addr;
    int sock = 0, valread;
    char buffer[1024] = {0};
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("
 Socket creation error 
");
        return -1;
    }
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8080);
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
        printf("
Invalid address/ Address not supported 
");
        return -1;
    }
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("
Connection Failed 
");
        return -1;
    }
    char message[] = "GET / HTTP/1.1
Host: localhost
Connection: close

";
    send(sock, message, strlen(message), 0);
    
    while ((valread = read(sock, buffer, 1023)) > 0) {
        buffer[valread] = '';
        printf("%s", buffer);
    }
    
    return 0;
}

使用码云连接:https://gitee.com/li_ye_da/rocedu/tree/master/web
运行截图:
实验四 Web服务器2
实验四 Web服务器2
实验四 Web服务器2
实验四 Web服务器2
实验四 Web服务器2

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...