#include
#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, i, nbyte;
char buf[N];
struct sockaddr_in myaddr;
fd_set global_rdfs, current_rdfs;
if (argc < 3)
{
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);
FD_ZERO(&global_rdfs);
FD_SET(listenfd, &global_rdfs);
maxfd = listenfd;
while ( 1 )
{
current_rdfs = global_rdfs;
if (select(maxfd+1, ¤t_rdfs, NULL, NULL, NULL) < 0)
{
perror("fail to select");
exit(-1);
}
for (i=0; i<=maxfd; i++)
{
if ( FD_ISSET(i, ¤t_rdfs) )
{
if (i == listenfd)
{
printf("new connection\n");
if ((connfd = accept(i, NULL, NULL)) < 0)
{
perror("fail to accept");
exit(-1);
}
FD_SET(connfd, &global_rdfs);
maxfd = maxfd > connfd ? maxfd : connfd;
}
else
{
if ((nbyte = recv(i, buf, N, 0)) == 0)
{
printf("peer closed\n");
FD_CLR(i, &global_rdfs);
}
else
{
send(i, buf, nbyte, 0);
}
}
}
} // end for
}
return 0;
}
客户端实现代码:
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
char buf[N];
struct sockaddr_in servaddr;
if (argc < 3)
{
printf("Usage : %s \n", argv[0]);
exit(-1);
}
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("fail to socket");
exit(-1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = PF_INET;
servaddr.sin_port = htons(atoi(argv[2]));
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) < 0)
{
perror("fail to connect");
exit(-1);
}
while ( 1 )
{
printf("client > ");
fgets(buf, N, stdin);
if (strncmp(buf, "quit", 4) == 0)
{
close(sockfd);
exit(0);
}
send(sockfd, buf, N, 0);
bzero(buf, N);
recv(sockfd, buf, N, 0);
printf("recv from server : %s", buf);
}
return 0;
}