#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#define BUFSIZE 255
int rw_opt(int rdfd,int wdfd)
{
int num;
char buf[BUFSIZE];
memset(buf,0,sizeof(buf));
num = read(rdfd,buf,sizeof(buf));
if(wdfd == 1)
write(1,">>>",3);
write(wdfd,buf,num);
if(strncmp(buf,"quit",4) == 0)
return 0;
return num;
}
int main()
{
int sockfd,ret;
int acceptfd;
struct sockaddr_in s_addr;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd == -1)
{
printf("socket error!
");
return 0;
}
memset(&s_addr,0,sizeof(struct sockaddr_in));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(1234);
s_addr.sin_addr.s_addr = htons(INADDR_ANY);
ret = bind(sockfd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
if(ret == -1)
{
printf("bind error!
");
return 0;
}
ret = listen(sockfd,5);
if(ret == -1)
{
printf("listen error!
");
return 0;
}
int addrlen = sizeof(struct sockaddr);
acceptfd = accept(sockfd,(struct sockaddr *)&s_addr,&addrlen);
if(acceptfd == -1)
{
printf("accept error!
");
}
else
{
printf("%s-----%d
",inet_ntoa(s_addr.sin_addr),ntohs(s_addr.sin_port));
}
fd_set rdfds;
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 1000;
while(1)
{
FD_ZERO(&rdfds);
FD_SET(0,&rdfds);
FD_SET(acceptfd,&rdfds);
ret = select(acceptfd+1,&rdfds,NULL,NULL,&timeout);
if(ret < 0)
{
printf("polling Monitor failed!
");
continue;
}
if(FD_ISSET(0,&rdfds))
{
ret = rw_opt(0,acceptfd);
if(ret == 0)
break;
}
if(FD_ISSET(acceptfd,&rdfds))
{
ret = rw_opt(acceptfd,1);
if(ret == 0)
break;
}
}
close(acceptfd);
close(sockfd);
return 0;
}