服务器程序:
int main()
{
int listenfd, connnfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9877);
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(struct sockaddr));
listen(listenfd, 5);
for(;;)
{
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);
if((childpid = fork()) == 0)
{
close(listenfd);
str_echo(connfd);
exit(0);
}
}
close(connfd);
}
void str_echo(int sockfd);
{
size_t n;
char buff[MAXFILE];
again:
while((n=read(sockfd, buff, MAXFILE)) > 0)
write(sockfd, buf, n);
if(n<0 && errno == EINTR)
goto again;
else if(n < 0)
err_sys("str_echo error");
}
客户端:
int main()
{
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SCOK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.family = AF_INET;
servaddr.sin_port = htons(9877);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
connect(sockfd, (struct sockaddr)&servaddr, sizeof(struct sockaddr));
str_cli(stdin, sockfd);
exit(0);
}
str_cli(FILE* fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
while(fgets(sendline, MAXLINE, fp) != NULL)
{
write(sockfd, sendline, srelen(sendline));
if(readline(sockfd, recvline, MAXLINE) == 0)
printf("error");
fputs(recvline, stdout);
}
}
阅读(2028) | 评论(0) | 转发(1) |