分类:
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);
}