首页 > 编程语言 >2023-2024-1 20211327 实验四 Web服务器1-socket编程

2023-2024-1 20211327 实验四 Web服务器1-socket编程

时间:2023-12-08 11:57:03浏览次数:58  
标签:Web socket server 2024 client time include addr

实验四 Web服务器1-socket编程

time服务器的客户端服务器

time_server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>

void handle_client(int client_socket) {
    time_t current_time;
    char time_string[50];
    
    // Get current time
    time(&current_time);
    snprintf(time_string, sizeof(time_string), "%s", ctime(&current_time));

    // Send current time to the client
    send(client_socket, time_string, strlen(time_string), 0);

    close(client_socket);
}

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    // Create socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Error creating socket");
        exit(EXIT_FAILURE);
    }

    // Bind socket to address and port
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(12345); // Use a specific port number, e.g., 12345

    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error binding socket");
        exit(EXIT_FAILURE);
    }

    // Listen for incoming connections
    if (listen(server_socket, 5) == -1) {
        perror("Error listening for connections");
        exit(EXIT_FAILURE);
    }

    printf("Time Server listening on port 12345...\n");

    while (1) {
        // Accept connection from client
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
        if (client_socket == -1) {
            perror("Error accepting connection");
            continue;
        }

        printf("Accepted connection from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        // Fork a child process to handle the client
        if (fork() == 0) {
            // Child process
            close(server_socket);  // Close server socket in child process
            handle_client(client_socket);
            exit(EXIT_SUCCESS);
        } else {
            // Parent process
            close(client_socket);  // Close client socket in parent process
            waitpid(-1, NULL, WNOHANG);  // Reap zombie processes
        }
    }

    return 0;
}

time_client.c

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

void time_client() {
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        perror("Error creating socket");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Replace with your server's IP address
    server_addr.sin_port = htons(12345); // Use the port number used by the time server

    if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error connecting to the server");
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    char buffer[1024];
    ssize_t recv_size = recv(client_socket, buffer, sizeof(buffer) - 1, 0);
    if (recv_size <= 0) {
        perror("Error receiving data");
    } else {
        buffer[recv_size] = '\0'; // Null-terminate the received data
        printf("Time from server: %s", buffer);
    }

    close(client_socket);
}

int main() {
    // Time Client
    printf("Time Client:\n");
    time_client();

    return 0;
}

echo服务器的客户端服务器

echo_server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>

void handle_echo(int client_socket) {
    char buffer[1024];
    int pid = getpid();
    char student_id[] = "20211327";
    char name[] = "sjx";

    // Receive data from client
    ssize_t recv_size = recv(client_socket, buffer, sizeof(buffer), 0);
    if (recv_size <= 0) {
        perror("Error receiving data");
        close(client_socket);
        return;
    }

    // Process data and prepare response
    char response[1024];
    int snprintf_result = snprintf(response, sizeof(response), "Server process pid %d %s %s echo: %s",
                                   pid, student_id, name, buffer);

    if (snprintf_result < 0 || snprintf_result >= sizeof(response)) {
        // Handle error or truncate situation
        perror("Error formatting response");
        close(client_socket);
        return;
    }

    // Send response to the client
    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 client_addr_len = sizeof(client_addr);

    // Create socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Error creating socket");
        exit(EXIT_FAILURE);
    }

    // Bind socket to address and port
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(12346); // Use a different port number, e.g., 12346

    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error binding socket");
        exit(EXIT_FAILURE);
    }

    // Listen for incoming connections
    if (listen(server_socket, 5) == -1) {
        perror("Error listening for connections");
        exit(EXIT_FAILURE);
    }

    printf("Echo Server listening on port 12346...\n");

    while (1) {
        // Accept connection from client
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
        if (client_socket == -1) {
            perror("Error accepting connection");
            continue;
        }

        printf("Accepted connection from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        // Fork a child process to handle the client
        if (fork() == 0) {
            // Child process
            close(server_socket);  // Close server socket in child process
            handle_echo(client_socket);
            exit(EXIT_SUCCESS);
        } else {
            // Parent process
            close(client_socket);  // Close client socket in parent process
            waitpid(-1, NULL, WNOHANG);  // Reap zombie processes
        }
    }

    return 0;
}

echo_client.c

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

void echo_client() {
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        perror("Error creating socket");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Replace with your server's IP address
    server_addr.sin_port = htons(12346); // Use the port number used by the echo server

    if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("Error connecting to the server");
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    char message[] = "Hello, server!"; // Replace with your message
    send(client_socket, message, strlen(message), 0);

    char buffer[1024];
    ssize_t recv_size = recv(client_socket, buffer, sizeof(buffer) - 1, 0);
    if (recv_size <= 0) {
        perror("Error receiving data");
    } else {
        buffer[recv_size] = '\0'; // Null-terminate the received data
        printf("Response from server: %s\n", buffer);
    }

    close(client_socket);
}

int main() {
    // Echo Client
    printf("\nEcho Client:\n");
    echo_client();

    return 0;
}

运行截图

标签:Web,socket,server,2024,client,time,include,addr
From: https://www.cnblogs.com/shen-jianxiang/p/17884850.html

相关文章

  • 实验四-2 Web
    代码#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<stdlib.h>#include<errno.h>#include<string.h>#include<netdb.h>#include<arpa/inet.h>#includ......
  • ubuntu 非 root用户 bind socket 80端口 失败
    在Ubuntu或其他类似的Linux系统中,非root用户在绑定低于1024的端口时会失败,这是出于安全考虑的一种行为。为了允许非root用户绑定低端口,您可以考虑以下几种方法:1.使用CAP_NET_BIND_SERVICE能力您可以使用setcap命令,为您的可执行文件分配CAP_NET_BIND_SERVICE能......
  • Web服务器-socket编程
    代码#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<stdlib.h>#include<errno.h>#include<string.h>#include<netdb.h>#include<arpa/inet.h>#includ......
  • 第4章 带你快速入门WebRTC技术
    4-3屏幕共享项目-用golang搭建静态资源服务这段代码是一个使用Go语言编写的简单的HTTP和HTTPS服务器。下面是对代码中涉及的知识点和语法格式的详细解释packagemainimport( "fmt" "net/http")packagemain:这行代码指定了当前文件所属的包是main,表示这是一个可执行程......
  • 实验四 Web服务器2
    一、任务基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用LinuxSocket实现:Web服务器的客户端服务器,提交程序运行截图实现GET即可,请求,响应要符合HTTP协议规范服务器部署到华为云服务器,浏览器用本机的把服务器部署到试验箱。(加分项)......
  • JavaWeb - Day03 - Ajax、前端工程化、Element
    01.Ajax-介绍Ajax概念:AsynchronousJavaScriptAndXML,异步的JavaScript和XML。作用:数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用的校验等等......
  • 记录springboot的一次使用socketio的经历
    pom中加入依赖<dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>2.0.6</version></dependency>......
  • # 2023-2024-1 20231308 《计算机基础与程序设计》第十一周学习总结
    2023-2024-120231308《计算机基础与程序设计》第十一周学习总结作业信息这个作业属于哪个课程2023-2024-1-计算机基础与程序设计这个作业要求在哪里2023-2024-1计算机基础与程序设计第十一周作业这个作业的目标计算机网络,网络拓扑,云计算,网络安全,Web,HTML,CSS,Javas......
  • 实验四 Web服务器2
    实验四Web服务器2基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用LinuxSocket实现:1.Web服务器的客户端服务器,提交程序运行截图2.实现GET即可,请求,响应要符合HTTP协议规范3.服务器部署到华为云服务器,浏览器用本机的4.把服务器部署到试验箱。(加分项)web_server.c1#include......
  • 实验四 Web服务器2
    server.c#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#definePORT8080#defineBUFFER_SIZE1024intmain(){   int......