1#include "Acceptor.h" 2#include "InetAddress.h" 3#include "TcpStream.h" 4 5#include <thread> 6#include <vector> 7 8#include <assert.h> 9#include <string.h> 10#include <sys/time.h> 11 12double now() 13{ 14 struct timeval tv = { 0, 0 }; 15 gettimeofday(&tv, NULL); 16 return tv.tv_sec + tv.tv_usec / 1000000.0; 17} 18 19// an interative request-response server 20int main(int argc, char* argv[]) 21{ 22 InetAddress listenAddr(3210); 23 Acceptor acceptor(listenAddr); 24 printf("Accepting... Ctrl-C to exit\n"); 25 int count = 0; 26 bool nodelay = argc > 1 && strcmp(argv[1], "-D") == 0; 27 while (true) 28 { 29 TcpStreamPtr tcpStream = acceptor.accept(); 30 printf("accepted no. %d client\n", ++count); 31 if (nodelay) 32 tcpStream->setTcpNoDelay(true); 33 34 while (true) 35 { 36 int len = 0; 37 int nr = tcpStream->receiveAll(&len, sizeof len); 38 if (nr <= 0) 39 break; 40 printf("%f received header %d bytes, len = %d\n", now(), nr, len); 41 assert(nr == sizeof len); 42 43 std::vector<char> payload(len); 44 nr = tcpStream->receiveAll(payload.data(), len); 45 printf("%f received payload %d bytes\n", now(), nr); 46 assert(nr == len); 47 int nw = tcpStream->sendAll(&len, sizeof len); 48 assert(nw == sizeof len); 49 } 50 51 printf("no. %d client ended.\n", count); 52 } 53} 54