#include "common.h"
#include "thpool.h"

#define NTHREADS   4
#define SBUFSIZE   16

typedef struct _param {
   int hit;
   int conn_sock;
} param;

void toggle(int conn_sock,int hit);
void handle_request( void *arg) ;

void toggle(int conn_sock,int hit) 
{
    size_t n; int i,no=0;
    char buf[MAXLINE]; 

    
    while((n =recv(conn_sock, buf, MAXLINE,0))> 0) {
	printf("toggle服务器收到第%d个客户第%d个消息,长度为%d字节\n", hit,++no,(int)n);

        for(i=0; i<n; i++)
            if(isupper(buf[i])) 
                buf[i]=tolower(buf[i]);
            else if(islower(buf[i]))
                buf[i]=toupper(buf[i]);
        //sleep(1);      
	send (conn_sock, buf, n, 0);
    }
    
}

//示例任务 
void handle_request(void *arg) 
{
    param* datap=(param *) arg;
    int conn_sock = datap->conn_sock;
    int hit = datap->hit;

    printf("第%d个客户通信开始\n",hit);
    //usleep(1);
    toggle(conn_sock,hit);
    printf("第%d个客户通信结束\n",hit);
    
    free(arg);
    close(conn_sock);
}

//主函数
int main(int argc, char **argv) {

    int listen_sock, conn_sock, port,i; 
    struct sockaddr_in clientaddr; 
    struct hostent *hp;
    char *haddrp;
    int hit;
 
    int nth[NTHREADS];
    
    socklen_t clientlen=sizeof(struct sockaddr_in);

    if (argc != 2) {
	    fprintf(stderr, "usage: %s <port>\n", argv[0]);
	    exit(1);
    }
    
    listen_sock = open_listen_sock(port);
    if( listen_sock==-1) {
    	printf("端口号%d繁忙\n",port);
    	exit(1);
    }    
    
    port = atoi(argv[1]);
    
    listen_sock = open_listen_sock(port);
    if( listen_sock==-1) {
    	printf("端口号%d繁忙\n",port);
    	exit(1);
    }

    printf("start main\n");
    // 初始化线程池
    thpool_* pool = thpool_init(NTHREADS);

    // 创建示例任务并将其添加到线程池
     for (hit=1; ; hit++) { 
	    conn_sock = accept(listen_sock, (SA *) &clientaddr, &clientlen);
	    
           //determine the domain name and IP address of the client 
	    hp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, 
			   sizeof(clientaddr.sin_addr.s_addr), AF_INET);
	    haddrp = inet_ntoa(clientaddr.sin_addr);
	    //printf("server connected to %s (%s)\n", hp->h_name, haddrp);
	               
            param *new_param = (param*) malloc(sizeof(param));
            
            new_param->hit = hit;   
            new_param->conn_sock=conn_sock;

	    thpool_add_work(pool,handle_request, (void*)new_param); 
    }
    
    // 等待线程池中的所有任务执行完毕
    thpool_wait(pool);

    // 销毁线程池
    thpool_destroy(pool);

    printf("stop main\n");
    return 0;
}
