Daily Archives: 2019年1月22日

多线程并发服务器程序

1、server.c

#include "wrap.h"
#include <pthread.h>
#include <ctype.h>
#include <strings.h>

void *callback(void *arg)
{
    int *cfd = (int *)arg;
    printf("pthread %ld running...\n", pthread_self());
    while(1){
        char buf[BUFSIZ];
        int n = Readn(*cfd, buf, BUFSIZ);
        if (n <= 0){
            close(*cfd);
            pthread_exit(NULL);
        }
        int i = n;
        while(i--){
            buf[i] = toupper(buf[i]);
        }
        write(*cfd, buf, n);
    }
    return NULL;
}
#define SEV_PORT 3000
int main(){
    // 1、socket
    int sfd = Socket(AF_INET, SOCK_STREAM, 0);
    // 2、bind
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(SEV_PORT);
    Bind(sfd, &addr, sizeof(addr));
    // 3、listen
    Listen(sfd, 128);
    // 4、accept
    int cfds[256];
    int n = 0;
    while(1){
        struct sockaddr_in c_addr;
        socklen_t len = sizeof(c_addr);
        bzero(&c_addr, sizeof(c_addr));
        cfds[n] = Accept(sfd, &c_addr, &len);
        char buf[BUFSIZ];
        printf("Client connected -- ip:%s, port:%d\n", inet_ntop(AF_INET, &c_addr.sin_addr.s_addr, buf, BUFSIZ), ntohs(c_addr.sin_port));
        pthread_t thread;
        int ret = pthread_create(&thread, NULL, callback, cfds + n);
        if (ret < 0){
            perror("pthread create error");
            exit(1);
        }
        n++;
        pthread_detach(thread);
    }
}

wrap.h[……]

继续阅读