1569528b0SShuo Chen#include "Acceptor.h" 2569528b0SShuo Chen#include "InetAddress.h" 3569528b0SShuo Chen#include "TcpStream.h" 4569528b0SShuo Chen 5569528b0SShuo Chen#include <thread> 6569528b0SShuo Chen#include <vector> 7569528b0SShuo Chen 8569528b0SShuo Chen#include <assert.h> 9569528b0SShuo Chen#include <string.h> 10569528b0SShuo Chen#include <sys/time.h> 11569528b0SShuo Chen 12569528b0SShuo Chendouble now() 13569528b0SShuo Chen{ 14569528b0SShuo Chen struct timeval tv = { 0, 0 }; 15569528b0SShuo Chen gettimeofday(&tv, NULL); 16569528b0SShuo Chen return tv.tv_sec + tv.tv_usec / 1000000.0; 17569528b0SShuo Chen} 18569528b0SShuo Chen 19b42ce01eSShuo Chen// an interative request-response server 20b42ce01eSShuo Chenint main(int argc, char* argv[]) 21569528b0SShuo Chen{ 22569528b0SShuo Chen InetAddress listenAddr(3210); 23569528b0SShuo Chen Acceptor acceptor(listenAddr); 24569528b0SShuo Chen printf("Accepting... Ctrl-C to exit\n"); 25569528b0SShuo Chen int count = 0; 26b42ce01eSShuo Chen bool nodelay = argc > 1 && strcmp(argv[1], "-D") == 0; 27569528b0SShuo Chen while (true) 28569528b0SShuo Chen { 29569528b0SShuo Chen TcpStreamPtr tcpStream = acceptor.accept(); 30569528b0SShuo Chen printf("accepted no. %d client\n", ++count); 31b42ce01eSShuo Chen if (nodelay) 32b42ce01eSShuo Chen tcpStream->setTcpNoDelay(true); 33569528b0SShuo Chen 34b42ce01eSShuo Chen while (true) 35b42ce01eSShuo Chen { 36b42ce01eSShuo Chen int len = 0; 37b42ce01eSShuo Chen int nr = tcpStream->receiveAll(&len, sizeof len); 38b42ce01eSShuo Chen if (nr <= 0) 39b42ce01eSShuo Chen break; 40b42ce01eSShuo Chen printf("%f received header %d bytes, len = %d\n", now(), nr, len); 41b42ce01eSShuo Chen assert(nr == sizeof len); 42b42ce01eSShuo Chen 43b42ce01eSShuo Chen std::vector<char> payload(len); 44b42ce01eSShuo Chen nr = tcpStream->receiveAll(payload.data(), len); 45b42ce01eSShuo Chen printf("%f received payload %d bytes\n", now(), nr); 46b42ce01eSShuo Chen assert(nr == len); 47b42ce01eSShuo Chen int nw = tcpStream->sendAll(&len, sizeof len); 48b42ce01eSShuo Chen assert(nw == sizeof len); 49b42ce01eSShuo Chen } 50569528b0SShuo Chen 51569528b0SShuo Chen printf("no. %d client ended.\n", count); 52569528b0SShuo Chen } 53569528b0SShuo Chen} 54