1#include "Acceptor.h"
2#include "InetAddress.h"
3#include "TcpStream.h"
4
5#include <thread>
6#include <string.h>
7
8// a thread-per-connection current echo server
9int main(int argc, char* argv[])
10{
11  bool nodelay = false;
12  bool ipv6 = false;
13  for (int i = 1; i < argc; ++i) {
14    if (strcmp(argv[i], "-6") == 0)
15      ipv6 = true;
16    if (strcmp(argv[i], "-D") == 0)
17      nodelay = true;
18  }
19  InetAddress listenAddr(3007, ipv6);
20  Acceptor acceptor(listenAddr);
21  printf("Listen on port 3007\n");
22  printf("Accepting... Ctrl-C to exit\n");
23  int count = 0;
24
25  while (true)
26  {
27    TcpStreamPtr tcpStream = acceptor.accept();
28    printf("accepted no. %d client\n", ++count);
29    if (nodelay)
30      tcpStream->setTcpNoDelay(true);
31
32    // C++11 doesn't allow capturing unique_ptr in lambda, C++14 allows.
33    std::thread thr([count] (TcpStreamPtr stream) {
34      printf("thread for no. %d client started.\n", count);
35      char buf[4096];
36      int nr = 0;
37      while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0)
38      {
39        int nw = stream->sendAll(buf, nr);
40        if (nw < nr)
41        {
42          break;
43        }
44      }
45      printf("thread for no. %d client ended.\n", count);
46    }, std::move(tcpStream));
47    thr.detach();
48  }
49}
50