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

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

时间:2023-12-07 14:24:09浏览次数:31  
标签:Web socket 编程 sock server client time include

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

1. time服务器的客户端服务器,提交程序运行截图

3. 服务器部署到华为云服务器,客户端用Ubuntu虚拟机。

time服务器代码(tms.c)

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

#define PORT 8080

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    time_t current_time;
    struct tm * time_info;
    char timeString[40];  // space to hold the time string

    // Creating socket file descriptor
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // Setting up the address structure
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // Bind the socket to the address
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // Listen for connections
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // Accept a connection
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    // Get the current time and format it
    time(&current_time);
    time_info = localtime(&current_time);
    strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", time_info);

    // Send the time to the client
    send(new_socket, timeString, strlen(timeString), 0);
    printf("Time sent to client\n");

    return 0;
}

time客户端代码(tmc.c)

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

#define PORT 8080

int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;
    char buffer[1024] = {0};

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("\n Socket creation error \n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // Convert IPv4 and IPv6 addresses from text to binary form
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("\nConnection Failed \n");
        return -1;
    }

    read(sock, buffer, 1024);
    printf("Time from server: %s\n", buffer);

    return 0;
}

2. echo服务器的客户端服务器,提交程序运行截图,服务器把客户端传进来的内容加入“服务器进程pid 你的学号 姓名 echo :”返回给客户端

echo服务器代码(ecs.c)

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

#define PORT 8081

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    char response[1024];

    // Creating socket file descriptor
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // Setting up the address structure
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // Bind the socket to the address
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // Listen for connections
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // Accept a connection
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    // Read the message from client
    read(new_socket, buffer, 1024);
    printf("Received from client: %s\n", buffer);

    // Prepare the response
    sprintf(response, "Server PID %d 20211125 苗靖章 echo: %s", getpid(), buffer);

    // Send the response back to client
    send(new_socket, response, strlen(response), 0);
    printf("Response sent to client\n");

    return 0;
}

echo客户端代码(ecc.c)

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

#define PORT 8081

int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;
    char buffer[1024] = {0};
    char *message = "Hello from client";

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("\n Socket creation error \n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // Convert IPv4 and IPv6 addresses from text to binary form
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("\nConnection Failed \n");
        return -1;
    }

    send(sock, message, strlen(message), 0);
    printf("Message sent to server\n");

    read(sock, buffer, 1024);
    printf("Response from server: %s\n", buffer);

    return 0;
}

4. 要用多线程或者多进程实现,至少连接两个客户端。

更新echo代码

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

#define PORT 8081
#define MAX_CLIENTS 10

void *client_handler(void *socket_desc) {
    int sock = *(int*)socket_desc;
    int read_size;
    char client_message[1024];
    char response[1024];

    // Read the message from client
    while ((read_size = recv(sock, client_message, sizeof(client_message), 0)) > 0) {
        client_message[read_size] = '\0'; // Null-terminate the string

        // Prepare the response
        sprintf(response, "Server PID %d 20211125 苗靖章 echo: %s", getpid(), client_message);

        // Send the response back to client
        send(sock, response, strlen(response), 0);
    }

    if (read_size == 0) {
        puts("Client disconnected");
    } else if (read_size == -1) {
        perror("recv failed");
    }

    free(socket_desc);
    return 0;
}

int main() {
    int server_fd, client_sock, *new_sock;
    struct sockaddr_in server, client;
    int c = sizeof(struct sockaddr_in);

    // Create socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == -1) {
        perror("Could not create socket");
        return 1;
    }

    // Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(PORT);

    // Bind
    if (bind(server_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
        perror("bind failed");
        return 1;
    }

    // Listen
    listen(server_fd, MAX_CLIENTS);

    // Accept incoming connections
    puts("Waiting for incoming connections...");
    while ((client_sock = accept(server_fd, (struct sockaddr *)&client, (socklen_t*)&c))) {
        puts("Connection accepted");

        pthread_t sniffer_thread;
        new_sock = malloc(1);
        *new_sock = client_sock;

        if (pthread_create(&sniffer_thread, NULL, client_handler, (void*) new_sock) < 0) {
            perror("could not create thread");
            return 1;
        }

        // Optionally, you can detach the thread for concurrent handling
        // pthread_detach(sniffer_thread);
    }

    if (client_sock < 0) {
        perror("accept failed");
        return 1;
    }

    return 0;
}

更新time代码:

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

#define PORT 8080

void *client_handler(void *socket_desc) {
    int sock = *(int*)socket_desc;
    time_t current_time;
    struct tm * time_info;
    char timeString[40];  // space to hold the time string

    // Get the current time and format it
    time(&current_time);
    time_info = localtime(&current_time);
    strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", time_info);

    // Send the time to the client
    write(sock, timeString, strlen(timeString));
    printf("Time sent to client\n");

    close(sock);
    free(socket_desc);
    return 0;
}

int main() {
    int server_fd, client_sock, *new_sock;
    struct sockaddr_in server, client;
    int c = sizeof(struct sockaddr_in);

    // Create socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == -1) {
        perror("Could not create socket");
        return 1;
    }

    // Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(PORT);

    // Bind
    if (bind(server_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
        perror("bind failed");
        return 1;
    }

    // Listen
    listen(server_fd, 3);

    // Accept incoming connections
    puts("Waiting for incoming connections...");
    while ((client_sock = accept(server_fd, (struct sockaddr *)&client, (socklen_t*)&c))) {
        puts("Connection accepted");

        pthread_t sniffer_thread;
        new_sock = malloc(1);
        *new_sock = client_sock;

        if (pthread_create(&sniffer_thread, NULL, client_handler, (void*) new_sock) < 0) {
            perror("could not create thread");
            return 1;
        }

        // Optionally, you can detach the thread for concurrent handling
        // pthread_detach(sniffer_thread);
    }

    if (client_sock < 0) {
        perror("accept failed");
        return 1;
    }

    return 0;
}

5. 把服务器部署到试验箱。(加分项)

标签:Web,socket,编程,sock,server,client,time,include
From: https://www.cnblogs.com/20211125mjz/p/17881879.html

相关文章

  • 实验四 Web服务器2
    基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用LinuxSocket实现:Web服务器的客户端服务器,提交程序运行截图实现GET即可,请求,响应要符合HTTP协议规范服务器部署到华为云服务器,浏览器用本机的把服务器部署到试验箱。(加分项)web服务器与客户端web_server.c#include<stdio.h>#inc......
  • 实验四 Web服务器1-socket编程
    基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用LinuxSocket实现:1.time服务器的客户端服务器,提交程序运行截图2.echo服务器的客户端服务器,提交程序运行截图,服务器把客户端传进来的内容加入“服务器进程pid你的学号姓名echo:”返回给客户端3.服务器部署到华为云服务器,客户端......
  • 配置webDriver(火狐浏览器)
    1.查看浏览器版本号在下载火狐浏览器的驱动之前,先确认自己火狐浏览器的版本号。火狐浏览器:设置 >常规>(下拉)Firefox更新,可以看到版本号。我的浏览器版本:120.0.1(64位)     如果想下载其他火狐浏览器的版本,可以到下面这个链接:https://ftp.mo......
  • 可视化学习:WebGL的基础使用
    引言继续复习可视化的学习。WebGL和其他Web端的图形系统存在很大的不同,是OpenGLES规范在浏览器的实现,它最大的不同就在于它更接近底层,可以由开发者直接操作GPU来实现绘图,性能很好,可以充分利用GPU并行计算的能力,并且WebGL还支持3D物体的渲染;WebGL最大的缺点应该就在于它的使用比......
  • ARM架构与编程--基于STM32F103 (1)LED原理图
    ARM架构与编程--基于STM32F103--(1)LED原理图--前言学习笔记《硬件知识_LED原理图》一、点亮一个led的步骤当我们学习C语言的时候,我们会写个Hello程序。那当我们写ARM程序,也该有一个简单的程序引领我们入门,这个程序就是点亮LED。我们怎样去点亮一个LED呢?分为三步:1.看原理图,确......
  • vue webpack 配置babel es6转化转化es5
    1、安装相关依赖npmi-D@babel/[email protected]@babel/[email protected]@8.0.6//语法中有asyncawait等npmi-D@babel/[email protected]@babel/[email protected]、babel.config.jsmodule.exports={pres......
  • Web_XCTF/BUUCTF_WriteUp | warmup
    题目分析F12查看源码,发现注释<!--source.php-->,作为参数接入url提交,得到php代码:稍做分析:<?phphighlight_file(__FILE__);//对当前文件进行PHP语法高亮显示classemmm//构造类emmm{publicstaticfunctioncheckF......
  • 渐进式web全栈:blazor web app
    前言本文要说的这种开发模式,这种模式并不是只有blazor支持,js中有一样的方案next.jsnuxt.js;blazor还有很多其它内容,本文近关注渐进式开发模式。是的,前后端是主流,不过以下情况也许前后端分离并不是最好的选择:小公司,人员不多,利润不高,创业阶段能省则省个人开发者,接接私活,要么一......
  • Amazon WorkSpaces 推出 Amazon WorkSpaces Web
    今天,我们宣布全面推出AmazonWorkSpacesWeb。WorkSpacesWeb是我们的最终用户计算套件中的一项新功能,它是一项低成本的完全托管式WorkSpace,专用于辅助基于Web的安全工作负载。WorkSpacesWeb使得客户能够轻松、安全地为其员工提供对内部网站和软件即服务Web应用程序的访......
  • Amazon WorkSpaces 现在提供使用 WorkSpaces 流协议(WSP)的 Web Access
    企业一直需要找到相应的方案,以快速让用户从任何地点和任何计算机进行工作,同时保证安全性和生产力。为了使用WorkSpaces流协议(WSP)简化AmazonWorkSpaces的部署,同时无需安装原生的客户端应用程序,用户现在可以在Windows、macOS或Linux计算机上通过受支持的Web浏览器访问A......