Samchon Framework for CPP  1.0.0
Server.hpp
1 #pragma once
2 
3 #include <samchon/protocol/IServer.hpp>
4 #include <samchon/protocol/IClient.hpp>
5 
6 #include <iostream>
7 #include <fstream>
8 #include <iterator>
9 #include <thread>
10 
11 #include <samchon/ByteArray.hpp>
12 #include <samchon/protocol/Invoke.hpp>
13 
14 namespace samchon
15 {
16  namespace example
17  {
18  namespace invoke_binary
19  {
20 
21 class File
22 {
23 public:
24  std::string name;
25  std::string extension;
26  ByteArray data;
27 
28 public:
29  File(WeakString path)
30  {
31  // LOAD FILE
32  std::ifstream file(path.str(), std::ios::in | std::ios::binary);
33  file.unsetf(std::ios::skipws);
34 
35  std::istream_iterator<unsigned char> begin(file), end;
36 
37  data.assign(begin, end);
38  file.close();
39 
40  // SET NAME AND EXTENSION
41  path = path.substr(path.rfind("/") + 1);
42  name = path.between("", ".");
43  extension = path.between(".");
44  };
45 
46  auto toInvoke() const -> std::shared_ptr<protocol::Invoke>
47  {
48  //return std::make_shared<protocol::Invoke>("saveFile2", name, extension);
49  return std::make_shared<protocol::Invoke>("saveFile", name, extension, data);
50  };
51 };
52 
53 class Server
54  : public protocol::IServer,
55  public protocol::IClient
56 {
57 private:
58  typedef protocol::IServer super;
59 
60  std::vector<File> fileArray;
61 
62 public:
63  Server()
64  : super(),
65  protocol::IClient()
66  {
67  fileArray =
68  {
69  File("D:/cpp_class_diagram.pdf"),
70  File("D:/entity_relationship_diagram.pdf"),
71  File("D:/js_class_diagram.pdf"),
72  File("D:/sequence_diagram.pdf")
73  };
74  };
75 
76 protected:
77  virtual auto PORT() const -> int override
78  {
79  return 11711;
80  };
81  virtual void addClient(protocol::Socket *socket)
82  {
83  std::cout << "A client has connected." << std::endl;
84 
85  this->socket = socket;
86  listen();
87  };
88 
89 public:
90  virtual void sendData(std::shared_ptr<protocol::Invoke> invoke)
91  {
93  std::this_thread::sleep_for(std::chrono::milliseconds(100));
94  };
95  virtual void replyData(std::shared_ptr<protocol::Invoke> invoke)
96  {
97  std::cout << invoke->toXML()->toString() << std::endl;
98  if (invoke->getListener() != "getFile")
99  return;
100 
101  for (size_t i = 0; i < fileArray.size(); i++)
102  this->sendData(fileArray[i].toInvoke());
103  }
104 };
105 
106  };
107  };
108 };
Definition: RWMutex.hpp:4
virtual void sendData(std::shared_ptr< Invoke >)
Sends message to a related system.
Definition: IClient.cpp:309
Top level namespace of products built from samchon.
Definition: ByteArray.hpp:7