1#include <stdio.h>
2#include <sys/time.h>
3#include <unistd.h>
4
5#include "Acceptor.h"
6#include "InetAddress.h"
7#include "Socket.h"
8#include "TcpStream.h"
9
10
11void dump(const char* filename)
12{
13  char buf[65536];
14  FILE* fp = fopen(filename, "r");
15  if (fp)
16  {
17    ssize_t nr;
18    while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0)
19      fwrite(buf, 1, nr, stdout);
20
21    fclose(fp);
22  }
23}
24
25void snapshot(const char* name, int N)
26{
27  printf("===== %d %s =====\n", N, name);
28  dump("/proc/meminfo");
29  dump("/proc/slabinfo");
30}
31
32int main(int argc, char* argv[])
33{
34  const int N = argc > 1 ? atoi(argv[1]) : 1000;
35
36  snapshot("started", N);
37
38  InetAddress listenAddr(2222);
39  Acceptor acceptor(listenAddr);
40  snapshot("acceptor created", 1);
41
42  InetAddress serverAddr("127.0.0.1", 2222);
43
44  std::vector<Socket> clients;
45  clients.reserve(N);
46  for (int i = 0; i < N; ++i)
47    clients.push_back(Socket::createTCP(serverAddr.family()));
48  snapshot("clients created", N);
49
50  std::vector<Socket> servers;
51  servers.reserve(N);
52  for (int i = 0; i < N; ++i)
53  {
54    char buf[64];
55    const int ports_per_ip = 16384;
56    int clientIP = i / ports_per_ip;
57    snprintf(buf, sizeof buf, "127.1.%d.%d", clientIP / 128, clientIP % 128);
58    InetAddress localAddr(buf, 10000 + i % ports_per_ip);
59    clients[i].bindOrDie(localAddr);
60    if (i % 10000 == 0) {
61      struct timeval tv;
62      gettimeofday(&tv, NULL);
63      fprintf(stderr, "%ld.%06ld Client %d bind to %s\n", tv.tv_sec, tv.tv_usec, i, buf);
64    }
65    if (clients[i].connect(serverAddr))
66    {
67      perror("connect");
68      break;
69    }
70    servers.push_back(acceptor.acceptSocketOrDie());
71  }
72  snapshot("clients connected", N);
73
74  // TODO: epoll
75
76  servers.clear();
77  snapshot("servers disconnected", N);
78
79  clients.clear();
80  snapshot("clients disconnected", N);
81}
82