1efbfdb0cSShuo Chen#include "Acceptor.h"
2efbfdb0cSShuo Chen#include "InetAddress.h"
3efbfdb0cSShuo Chen#include "TcpStream.h"
4efbfdb0cSShuo Chen
5ddbf26c3SShuo Chen#include <thread>
6569528b0SShuo Chen#include <string.h>
7ddbf26c3SShuo Chen
8ddbf26c3SShuo Chen// a thread-per-connection current echo server
9569528b0SShuo Chenint main(int argc, char* argv[])
10efbfdb0cSShuo Chen{
1102165cfcSShuo Chen  bool nodelay = false;
1202165cfcSShuo Chen  bool ipv6 = false;
1302165cfcSShuo Chen  for (int i = 1; i < argc; ++i) {
1402165cfcSShuo Chen    if (strcmp(argv[i], "-6") == 0)
1502165cfcSShuo Chen      ipv6 = true;
1602165cfcSShuo Chen    if (strcmp(argv[i], "-D") == 0)
1702165cfcSShuo Chen      nodelay = true;
1802165cfcSShuo Chen  }
1902165cfcSShuo Chen  InetAddress listenAddr(3007, ipv6);
20efbfdb0cSShuo Chen  Acceptor acceptor(listenAddr);
2102165cfcSShuo Chen  printf("Listen on port 3007\n");
22ddbf26c3SShuo Chen  printf("Accepting... Ctrl-C to exit\n");
23ddbf26c3SShuo Chen  int count = 0;
2402165cfcSShuo Chen
25355c2bf7SShuo Chen  while (true)
26355c2bf7SShuo Chen  {
27355c2bf7SShuo Chen    TcpStreamPtr tcpStream = acceptor.accept();
28ddbf26c3SShuo Chen    printf("accepted no. %d client\n", ++count);
29569528b0SShuo Chen    if (nodelay)
30569528b0SShuo Chen      tcpStream->setTcpNoDelay(true);
31ddbf26c3SShuo Chen
32ddbf26c3SShuo Chen    // C++11 doesn't allow capturing unique_ptr in lambda, C++14 allows.
33ddbf26c3SShuo Chen    std::thread thr([count] (TcpStreamPtr stream) {
34ddbf26c3SShuo Chen      printf("thread for no. %d client started.\n", count);
35ddbf26c3SShuo Chen      char buf[4096];
36ddbf26c3SShuo Chen      int nr = 0;
37aafef3ccSShuo Chen      while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0)
38355c2bf7SShuo Chen      {
39ddbf26c3SShuo Chen        int nw = stream->sendAll(buf, nr);
40ddbf26c3SShuo Chen        if (nw < nr)
41ddbf26c3SShuo Chen        {
42ddbf26c3SShuo Chen          break;
43ddbf26c3SShuo Chen        }
44355c2bf7SShuo Chen      }
45ddbf26c3SShuo Chen      printf("thread for no. %d client ended.\n", count);
46ddbf26c3SShuo Chen    }, std::move(tcpStream));
47ddbf26c3SShuo Chen    thr.detach();
48355c2bf7SShuo Chen  }
49efbfdb0cSShuo Chen}
50