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