unix网络编程----迭代式echo服务器与客户端(只支持一个客户端通信)

分别用gcc编译两个代码为可执行程序client和server之后,在一个终端里运行./server启动服务器,在另一个终端运行./client 127.0.0.1后,就可以在client终端里面输入任意字符然后回车,输入的字符会发送到服务器,然后被服务器返回来,在client终端里显示,起到"echo"的效果。此代码可以作为网络编程基础设置的参考。
参考资料:<>W.Richard Stevens,Bill Fenner,Andrew M.Rudoff

客户端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFFSIZE4096
#define SERV_PORT9877
#define SAstructsockaddr
#define LISTENQ 1024
#define STDIN_FILENO0
#define STDOUT_FILENO1
int
main(int argc, char **argv)
{
struct timevaltpstart,tpend;
charbuf[BUFFSIZE];
doubletimeuse;
int sockfd;
int tffd;
chartime[64];
ssize_t n;
structsockaddr_in servaddr;
if(argc != 2){
printf("usage: cmd /n");
exit(0);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
connect(sockfd, (SA *) &servaddr, sizeof(servaddr));
gettimeofday(&tpstart,NULL);
printf("time got!/n");
while(1)
{
if((n = read(STDIN_FILENO,buf,BUFFSIZE)) == 0)
break;
n = write(sockfd, buf, n);
n = read(sockfd, buf, BUFFSIZE);
n = write(STDOUT_FILENO,buf,n);
}
gettimeofday(&tpend,NULL);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
gcvt(timeuse, 10, time);
tffd = creat("time.txt", 0644);
write(tffd, time, 64);
close(tffd);
exit(0);
}

服务器代码:
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
#define SERV_PORT9877
#define SAstructsockaddr
#define LISTENQ 1024
int
main(int argc, char **argv)
{
int listenfd, connfd;
charbuf[MAXLINE];
ssize_t n;
pid_tchildpid;
socklen_tclilen;
structsockaddr_in cliaddr, servaddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
listen(listenfd, LISTENQ);
while(1){
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (SA *) &cliaddr, &clilen);
while(1)
{
if((n = read(connfd, buf, MAXLINE)) == 0)
break;

n = write(connfd,buf,n);
}
close(connfd);
}
}
【unix网络编程----迭代式echo服务器与客户端(只支持一个客户端通信)】

    推荐阅读