1b7176da7SShuo Chen#include "Acceptor.h"
2b7176da7SShuo Chen#include "InetAddress.h"
3b7176da7SShuo Chen#include "TcpStream.h"
4b7176da7SShuo Chen
5b7176da7SShuo Chen#include <thread>
6b7176da7SShuo Chen#include <unistd.h>
7b7176da7SShuo Chen
8b7176da7SShuo Chenvoid sender(const char* filename, TcpStreamPtr stream)
9b7176da7SShuo Chen{
10b7176da7SShuo Chen  FILE* fp = fopen(filename, "rb");
11b7176da7SShuo Chen  if (!fp)
12b7176da7SShuo Chen    return;
13b7176da7SShuo Chen
14b7176da7SShuo Chen  printf("Sleeping 10 seconds.\n");
15b7176da7SShuo Chen  sleep(10);
16b7176da7SShuo Chen
17b7176da7SShuo Chen  printf("Start sending file %s\n", filename);
18b7176da7SShuo Chen  char buf[8192];
19b7176da7SShuo Chen  size_t nr = 0;
20b7176da7SShuo Chen  while ( (nr = fread(buf, 1, sizeof buf, fp)) > 0)
21b7176da7SShuo Chen  {
22b7176da7SShuo Chen    stream->sendAll(buf, nr);
23b7176da7SShuo Chen  }
24b7176da7SShuo Chen  fclose(fp);
25b7176da7SShuo Chen  printf("Finish sending file %s\n", filename);
26b7176da7SShuo Chen
27b7176da7SShuo Chen  // Safe close connection
28b7176da7SShuo Chen  printf("Shutdown write and read until EOF\n");
29b7176da7SShuo Chen  stream->shutdownWrite();
30b7176da7SShuo Chen  while ( (nr = stream->receiveSome(buf, sizeof buf)) > 0)
31b7176da7SShuo Chen  {
32b7176da7SShuo Chen    // do nothing
33b7176da7SShuo Chen  }
34b7176da7SShuo Chen  printf("All done.\n");
35b7176da7SShuo Chen
36b7176da7SShuo Chen  // TcpStream destructs here, close the TCP socket.
37b7176da7SShuo Chen}
38b7176da7SShuo Chen
39b7176da7SShuo Chenint main(int argc, char* argv[])
40b7176da7SShuo Chen{
41b7176da7SShuo Chen  if (argc < 3)
42b7176da7SShuo Chen  {
43b7176da7SShuo Chen    printf("Usage:\n  %s filename port\n", argv[0]);
44b7176da7SShuo Chen    return 0;
45b7176da7SShuo Chen  }
46b7176da7SShuo Chen
47b7176da7SShuo Chen  int port = atoi(argv[2]);
48b7176da7SShuo Chen  Acceptor acceptor((InetAddress(port)));
49b7176da7SShuo Chen  printf("Accepting... Ctrl-C to exit\n");
50b7176da7SShuo Chen  int count = 0;
51b7176da7SShuo Chen  while (true)
52b7176da7SShuo Chen  {
53b7176da7SShuo Chen    TcpStreamPtr tcpStream = acceptor.accept();
54b7176da7SShuo Chen    printf("accepted no. %d client\n", ++count);
55b7176da7SShuo Chen
56b7176da7SShuo Chen    std::thread thr(sender, argv[1], std::move(tcpStream));
57b7176da7SShuo Chen    thr.detach();
58b7176da7SShuo Chen  }
59b7176da7SShuo Chen}
60