实现功能如下:
同时监听终端的输入和TCP的监听套接字
实现代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int listenfd, connfd, maxfd, n, i;
char buf[N];
struct sockaddr_in myaddr, cliaddr;
socklen_t clilen;
fd_set rdfs;
struct timeval mytime;
if (argc < 3)
{
printf("Usage : %s
\n", argv[0]);
exit(-1);
}
if ((listenfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("fail to socket");
exit(-1);
}
bzero(&myaddr, sizeof(myaddr));
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(atoi(argv[2]));
myaddr.sin_addr.s_addr = inet_addr(argv[1]);
if (bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) < 0)
{
perror("fail to bind");
exit(-1);
}
listen(listenfd, 5);
maxfd = listenfd;
while ( 1 )
{
FD_ZERO(&rdfs);
FD_SET(0, &rdfs);
FD_SET(listenfd, &rdfs);
mytime.tv_sec = 3;
mytime.tv_usec = 0;
if ((n = select(maxfd+1, &rdfs, NULL, NULL, &mytime)) < 0)
{
perror("fail to select");
exit(-1);
}
else if (n > 0)
{
for (i=0; i<=maxfd; i++)
{
if ( FD_ISSET(i, &rdfs) )
{
if (STDIN_FILENO == i)
{
fgets(buf, N, stdin);
printf("You input %d characters\n", strlen(buf));
}
if (i == listenfd)
{
clilen = sizeof(cliaddr);
if ((connfd = accept(listenfd, (SA *)&cliaddr, &clilen)) < 0)
{
perror("fail to accept");
exit(-1);
}
printf("connection from %s:%d\n", inet_ntoa(cliaddr.sin_addr),
ntohs(cliaddr.sin_port));
close(connfd);
}
}
} // end for
}
else // timeout
{
printf("timeout\n");
}
} // end while
return 0;
}
阅读(1205) | 评论(0) | 转发(0) |