guit  0.1
 All Classes Functions Variables Typedefs Enumerations Friends
gsocket.hpp
1 //
2 // Guit Sockets and Socket Channels.
3 // Guit GUI Toolkit
4 // Copyright © 2019/2020 Eric Lecolinet. All rights reserved.
5 // http://www.telecom-paris.fr/~elc
6 //
7 
8 #ifndef Guit_Socket_hpp
9 #define Guit_Socket_hpp
10 
11 #include <map>
12 #include <gtypes.hpp>
13 #include <gproplist.hpp>
14 namespace guit {
15 
16 namespace impl {
17 class GSocketBase;
18 class GSocketCnx;
19 class GSocketServer;
20 class GSocketNotifier;
21 }
22 class GSocket;
23 
24 
27 class GSocketChannel : public GObject {
28 public:
31 
38 
40  GSocketChannel& operator^=(GVarProp& synced_prop);
41 
43  GSocketChannel& operator<<(GFunction const& fun);
44 
46  GSocketChannel& operator=(GString const& data);
47 
49  GSocket* socket() {return sock_;}
50 
52  const GPropList& props() const {return props_;}
53 
54  GString typeName() const override {return "SocketChannel";}
55 
56 private:
57  friend class GSocket;
58  friend class impl::GSocketCnx;
59  friend class impl::GSocketNotifier;
60  GString name_;
61  gptr<GVarProp> recv_, sender_;
62  gptr<GSocket> sock_;
63  GPropList props_;
64  void sendValue();
65 };
66 
67 
68 
74 class GSocket : public GObject {
75 public:
77  enum Mode {Unstarted, Client, Server};
78 
83  enum Status {
84  Invalid = -3, UnknownHost = -2, CannotReach = -1,
85  Disconnected = 0, Connected = 1
86  };
87 
88  GSocket();
89  ~GSocket();
90 
92  Mode mode() const {return mode_;}
93 
95  GInt& status();
96 
99  bool startAsServer(int port);
100 
103  bool startAsClient(GString const& hostname, int port);
104 
106  void disconnect();
107 
118  GSocketChannel& operator[](GString const& name);
119 
125  void setSendBack(bool state) {dontsendback_ = !state;}
126 
127  GString typeName() const override {return "Socket";}
128 
129 protected:
130  friend class GSocketChannel;
131  friend class impl::GSocketServer;
132  friend class impl::GSocketCnx;
133 
134  void reset();
135  void clear();
136  void update();
137  void sendData(GString const&);
138  void disconnected(impl::GSocketBase*, GString const&);
139 
141  int maxattempts_{50};
142  Mode mode_{};
143  bool dontsendback_{};
144  gptr<GInt> status_;
145  std::map<GString, gptr<GSocketChannel>> channels_;
146  impl::GSocketBase* impl_{};
147 };
148 
149 }
150 #endif