一 个 多线程 socket,大家看看它有啥,缺点?

xiaopohaibebo 发布于 2013/11/10 22:40
阅读 375
收藏 0
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>

#define PORT 1234
#define BACKLONG 100
#define MAXCHARSIZE 100

void process_client (int connectfd,struct sockaddr_in client);
void *start_routine(void *arg);

struct ARG{
    int connfd;
    struct sockaddr_in client;
};
struct ARG *arg;
int main(void)
{
    int listenfd,connectfd;
    int sin_size;
    int opt = SO_REUSEADDR;
    struct sockaddr_in server,client;
    pthread_t tid;
    sin_size = sizeof(struct sockaddr_in);
    if((listenfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
    {
        perror("Create socket failed");
        exit(-1);

    }
    setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr= htonl(INADDR_ANY);
    if(bind(listenfd,(struct sockaddr *)&server,sizeof(struct sockaddr)) == -1)
    {
        perror("bind error");
        exit(-1);
    }
    if(listen(listenfd,BACKLONG) == -1)
    {
        perror("listen error");
        exit(-1);   
    }
    while(1)
    {
        if((connectfd = accept(listenfd,(struct sockaddr*)&client,&sin_size)) == -1)
        {
            perror("Accept error");
            exit(-1);             
        }
        arg = (struct ARG *)malloc(sizeof (struct ARG));
        arg->connfd = connectfd;
        memcpy((void *)&arg->client,&client,sizeof(client));
        if(pthread_create(&tid,NULL,start_routine,(void *)arg))
        {
            perror("pthread_create error\n");
            exit(-1);
        }
        
    }
    close(listenfd);

}
void *start_routine(void *arg)
{
    struct ARG *info;
    info = (struct ARG *)arg;
    process_client(info->connfd,info->client);
    free(arg);
    pthread_exit(NULL);       
}
void process_client(int connectfd, struct sockaddr_in client)
{
    ...........
    printf("Client(%s) disconnected\n",client_name);
    close(connectfd);
}

加载中
返回顶部
顶部