Chinaunix首页 | 论坛 | 博客
  • 博客访问: 442327
  • 博文数量: 85
  • 博客积分: 3580
  • 博客等级: 中校
  • 技术积分: 970
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-09 14:09
文章分类

全部博文(85)

文章存档

2011年(7)

2010年(78)

我的朋友

分类:

2010-06-23 11:27:32

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

struct sockargs {
 int s;
 struct sockaddr_in *remote;
 };

void* process_server(void *args) {
     int len,s;
     time_t ti;
     char buff[128];
     struct sockaddr_in *remote;
     struct sockargs connfd=*((struct sockargs *)args);
     s=connfd.s;
     remote=connfd.remote;
     pthread_detach(pthread_self());
     printf("connection from: %s:%d\n",inet_ntoa(remote->sin_addr),ntohs(remote->sin_port));
      ti=time(NULL);
      //snprintf(buff,sizeof(buff),"%s\r\n",ctime(&ti));
 while((len=recv(s,buff,sizeof(buff),0))>0) {
  buff[len]='\0';
       send(s, buff,strlen(buff), 0);
  bzero(buff,sizeof(buff));
 }

 free(remote);
 free(args);
 close(s);
 return(NULL);
}


int main(int argc, char **argv) {
    struct sockaddr_in *remote;
    char *hname, *sname;
    int s, c, len;
    pthread_t tid;
    struct sockargs *connfd;
    if(argc < 2)
     error(1,0,"parameters less than 2");
    else if(argc == 2) {
     hname = NULL;
 sname = argv[1];
    }
    else if(argc == 3) {
     hname = argv[1];
 sname = argv[2];
    }
    s = server(hname, sname,"tcp");
    len = sizeof(struct sockaddr);
    while(1) {
        remote=malloc(sizeof(struct sockaddr_in));
     if((c=accept(s,(struct sockaddr *)remote,&len))<=0)
         error(1,errno,"accept error!");
 connfd=(struct sockargs *)malloc(sizeof(struct sockargs));
 connfd->s=c;
 connfd->remote=remote;
 pthread_create(&tid,NULL,&process_server,(void *)connfd);
 
    }
    close(s);
    exit(0);
}

阅读(684) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~