828282

该代码示例展示了使用C语言和多线程技术构建的服务器程序,能同时处理多个客户端连接。服务器创建一个管理线程监控任务和工作线程数量,当有新连接时创建新线程处理客户端通信。客户端则连接到服务器,发送和接收消息,直至发送退出命令。
摘要由CSDN通过智能技术生成

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#include <pthread.h>

#define BUFFER_SIZE 1024

#define EXIT_MESSAGE "exit"

#define MAX_THREADS 10

void error(const char *message) {

    perror(message);

    exit(1);

}

typedef struct {

    int client_socket;

    int client_count;

} ClientInfo;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

int busy_threads = 0;

int task_count = 0;

void *handle_client(void *arg) {

    ClientInfo *client_info = (ClientInfo *)arg;

    int client_socket = client_info->client_socket;

    int client_count = client_info->client_count;

    char buffer[BUFFER_SIZE];

    printf("Client %d connected\n", client_count);

    while (1) {

        // 接收客户端消息

        memset(buffer, 0, sizeof(buffer));

        if (recv(client_socket, buffer, sizeof(buffer), 0) < 0) {

            error("Error receiving data");

        }

        printf("Client %d: %s\n", client_count, buffer);

        // 去除换行符

        buffer[strcspn(buffer, "\n")] = '\0';

        // 检查退出消息

        if (strcmp(buffer, EXIT_MESSAGE) == 0) {

            printf("Client %d exited\n", client_count);

            break;

        }

        // 发送消息给客户端

        printf("Server: ");

        fgets(buffer, sizeof(buffer), stdin);

        // 去除换行符

        buffer[strcspn(buffer, "\n")] = '\0';

        // 检查退出消息

        if (strcmp(buffer, EXIT_MESSAGE) == 0) {

            if (send(client_socket, buffer, strlen(buffer), 0) < 0) {

                error("Error sending data");

            }

            printf("You exited\n");

            break;

        }

        if (send(client_socket, buffer, strlen(buffer), 0) < 0) {

            error("Error sending data");

        }

    }

    // 关闭客户端套接字

    close(client_socket);

    // 释放内存

    free(client_info);

    pthread_mutex_lock(&mutex);

    busy_threads--;

    pthread_cond_signal(&condition);

    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);

}

void *manager_thread(void *arg) {

    while (1) {

        sleep(5);

        pthread_mutex_lock(&mutex);

        int num_tasks = task_count;

        int num_threads = busy_threads;

        pthread_mutex_unlock(&mutex);

        printf("Number of tasks: %d\n", num_tasks);

        printf("Number of busy threads: %d\n", num_threads);

        if (num_tasks > num_threads && num_threads < MAX_THREADS) {

            pthread_t tid;

            pthread_create(&tid, NULL, handle_client, NULL);

            pthread_mutex_lock(&mutex);

            busy_threads++;

            pthread_mutex_unlock(&mutex);

        } else if (num_tasks < num_threads) {

            pthread_mutex_lock(&mutex);

            pthread_cond_wait(&condition, &mutex);

            pthread_mutex_unlock(&mutex);

        }

    }

}

int main(int argc, char *argv[]) {

    if (argc != 2) {

        fprintf(stderr, "Usage: %s <port>\n", argv[0]);

        exit(1);

    }

    int server_socket, client_socket;

    char buffer[BUFFER_SIZE];

    struct sockaddr_in server_addr, client_addr;

    socklen_t client_addr_len;

    // 创建服务器套接字

    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    if (server_socket < 0) {

        error("Error opening socket");

    }

    // 设置服务器地址结构

    memset(&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;

    server_addr.sin_addr.s_addr = INADDR_ANY;

    server_addr.sin_port = htons(atoi(argv[1]));

    // 绑定服务器套接字到指定端口

    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {

        error("Error binding socket");

    }

    // 监听连接请求

    if (listen(server_socket, 5) < 0) {

        error("Error listening");

    }

    printf("Waiting for connections...\n");

    int client_count = 1;

    pthread_t manager_tid;

    pthread_create(&manager_tid, NULL, manager_thread, NULL);

    while (1) {

        // 接受客户端连接

        client_addr_len = sizeof(client_addr);

        client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);

        if (client_socket < 0) {

            error("Error accepting connection");

        }

        // 创建线程处理客户端通信

        pthread_t tid;

        ClientInfo *client_info = (ClientInfo *)malloc(sizeof(ClientInfo));

        client_info->client_socket = client_socket;

        client_info->client_count = client_count;

        pthread_create(&tid, NULL, handle_client, client_info);

        pthread_mutex_lock(&mutex);

        busy_threads++;

        task_count++;

        pthread_mutex_unlock(&mutex);

        client_count++;

    }

    // 关闭服务器套接字

    close(server_socket);

    return 0;

}

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#define BUFFER_SIZE 1024

#define EXIT_MESSAGE "exit"

void error(const char *message) {

    perror(message);

    exit(1);

}

int main(int argc, char *argv[]) {

    if (argc != 3) {

        fprintf(stderr, "Usage: %s <server_ip> <server_port>\n", argv[0]);

        exit(1);

    }

    int client_socket;

    char buffer[BUFFER_SIZE];

    struct sockaddr_in server_addr;

    // 创建客户端套接字

    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    if (client_socket < 0) {

        error("Error opening socket");

    }

    // 设置服务器地址结构

    memset(&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;

    server_addr.sin_addr.s_addr = inet_addr(argv[1]);

    server_addr.sin_port = htons(atoi(argv[2]));

    // 连接到服务器

    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {

        error("Error connecting to server");

    }

    printf("Connected to server\n");

    // 发送和接收消息,直到发送退出消息

    while (1) {

        // 发送消息给服务器

        printf("Client: ");

        fgets(buffer, sizeof(buffer), stdin);

        // 去除换行符

        buffer[strcspn(buffer, "\n")] = '\0';

        // 检查退出消息

        if (strcmp(buffer, EXIT_MESSAGE) == 0) {

            if (send(client_socket, buffer, strlen(buffer), 0) < 0) {

                error("Error sending data");

            }

            printf("You exited\n");

            break;

        }

        if (send(client_socket, buffer, strlen(buffer), 0) < 0) {

            error("Error sending data");

        }

        // 接收服务器消息

        memset(buffer, 0, sizeof(buffer));

        if (recv(client_socket, buffer, sizeof(buffer), 0) < 0) {

            error("Error receiving data");

        }

        printf("Server: %s\n", buffer);

    }

    // 关闭套接字

    close(client_socket);

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值