📄 tcpecho2.c
字号:
/* TCPecho.c - main, TCPecho */#include <unistd.h>#include <stdlib.h>#include <string.h>#include <stdio.h>#include <errno.h> /* Added by Krishna *//* 8-Jan-08: to measure time */#include <time.h>#include <sys/time.h>extern int errno;int TCPecho(const char *host, const char *service);int errexit(const char *format, ...);int connectTCP(const char *host, const char *service);#define LINELEN 255/*------------------------------------------------------------------------ * main - TCP client for ECHO service *------------------------------------------------------------------------ */intmain(int argc, char *argv[]){ char *host = "localhost"; /* host to use if none supplied */ char *service = "echo"; /* default service name */ switch (argc) { case 1: host = "localhost"; break; case 3: service = argv[2]; /* FALL THROUGH */ case 2: host = argv[1]; break; default: fprintf(stderr, "usage: TCPecho [host [port]]\n"); exit(1); } TCPecho(host, service); exit(0);}/*------------------------------------------------------------------------ * TCPecho - send input to ECHO service on specified host and print reply *------------------------------------------------------------------------ */intTCPecho(const char *host, const char *service){ char buf[LINELEN+1]; /* buffer for one line of text */ int s, n; /* socket descriptor, read count*/ int outchars, inchars; /* characters sent and received */ int i; /* to measure response time */ struct timeval t1; struct timeval t2; double totalTime; s = connectTCP(host, service); while (fgets(buf, sizeof(buf), stdin)) { buf[LINELEN] = '\0'; /* insure line null-terminated */ outchars = strlen(buf); totalTime = 0; /* send the string 10 times to echo server */ for(i=0; i<10; i++) { gettimeofday(&t1, 0); /* measure the start time */ (void) write(s, buf, outchars); /* read it back */ for (inchars = 0; inchars < outchars; inchars+=n ) { n = read(s, &buf[inchars], outchars - inchars); if (n < 0) errexit("socket read failed: %s\n", strerror(errno)); } gettimeofday(&t2, 0); /* measure the end time */ /* calculate the cumulative RTT */ totalTime += ( (t2.tv_sec*1000000 + t2.tv_usec) - (t1.tv_sec*1000000 + t1.tv_usec) ); } /* end for */ fputs(buf, stdout); printf("RTT = %lf usec\n", totalTime/10); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -