socket实现Tcp多线程并发服务器

代码

#include "wrap.h"
#include 
#include 
#include 
#include 

#define SERVER_PORT 8000
#define MAXLINE 8192

struct s_info {
                          //定义一个结构体, 将地址结构跟cfd捆绑
    struct sockaddr_in cliaddr;
    int connfd;
};

void *do_work(void *arg)
{
     
    int n,i;
    struct s_info *ts = (struct s_info*)arg;
    char buf[MAXLINE];
    char str[INET_ADDRSTRLEN];      //#define INET_ADDRSTRLEN 16  可用"[+d"查看

    while (1) {
     
        n = Read(ts->connfd, buf, MAXLINE);                     //读客户端
        if (n == 0) {
     
            printf("the client %d closed...\n", ts->connfd);
            break;                                              //跳出循环,关闭cfd
        }
        printf("received from %s at PORT %d\n",
                inet_ntop(AF_INET, &(*ts).cliaddr.sin_addr, str, sizeof(str)),
                ntohs((*ts).cliaddr.sin_port));                 //打印客户端信息(IP/PORT)

        for (i = 0; i < n; i++) 
            buf[i] = toupper(buf[i]);                           //小写-->大写

        Write(STDOUT_FILENO, buf, n);                           //写出至屏幕
        Write(ts->connfd, buf, n);                              //回写给客户端
    }
    Close(ts->connfd);

    return (void *)0;
}

int main(int argc, char *argv[])
{
     
    struct sockaddr_in server_addr, client_addr;
    int listen_fd, connect_fd;
    socklen_t client_addr_len;
    pthread_t tid;
    int ret, i=0;

    struct s_info ts[256];

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    listen_fd = Socket(AF_INET, SOCK_STREAM, 0);
    Bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    Listen(listen_fd, 128);
    
    printf("Accept connections ...");
    while(1)
    {
     
        client_addr_len = sizeof(client_addr);
        connect_fd = Accept(listen_fd, (struct sockaddr *)&client_addr, &client_addr_len);
        ts[i].cliaddr = client_addr;
        ts[i].connfd = connect_fd;

        pthread_create(&tid, NULL, do_work, (void*)&ts[i]);
        pthread_detach(tid);                                                    //子线程分离,防止僵线程产生.
        i++;
    }

    return 0;
}

你可能感兴趣的:(Linux,socket,多线程)