客户服务器设计范式之迭代服务器,不过这种服务器使用范围很有限,因为这种服务器无法处理已等待服务的新用户。
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main(int argc , char** argv)
{
int sockfd,n;
char recvline[1024];
struct sockaddr_in seraddr;
if(argc !=2)
{
printf("argc error\r\n");
return 0;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket error\r\n");
return 0;
}
bzero(&seraddr, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(13000);
if((inet_pton(AF_INET, argv[1], &seraddr.sin_addr)) < 0)
{
printf("inet_pton error\r\n");
return 0;
}
if(connect(sockfd, (struct sockaddr*)&seraddr, sizeof(seraddr)) < 0)
{
printf("connect error\r\n");
return 0;
}
while((n = read(sockfd, recvline, 1023)) > 0)
{
recvline[n]=0;
if(fputs(recvline, stdout) == EOF)
{
printf("fputs error\r\n");
return 0;
}
}
if(n < 0)
{
printf("read error\r\n");
}
return 0;
}
运行结果如下:
[root@localhost lytest]# ./a.out 202.85.220.122
Fri Oct 9 23:36:50 2015
#include <time.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
int listenfd, connectfd;
struct sockaddr_in servaddr;
char buf[1024];
time_t ticks;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("sock error\r\n");
return 0;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13000);
servaddr.sin_addr.s_addr = inet_addr("202.85.220.122");
if( bind(listenfd, (struct sockaddr* )&servaddr, sizeof(servaddr)) < 0)
{
printf("bind error\r\n");
return 0;
}
if(listen(listenfd, 0) < 0)
{
printf("listen error\r\n");
return 0;
}
for( ; ;)
{
connectfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
ticks = time(NULL);
snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&ticks));
write(connectfd, buf, strlen(buf));
close(connectfd);
}
}